Beruflich Dokumente
Kultur Dokumente
STATUS=1(Ready State): The initial state of Node N STATUS=2(Waiting State): Node N is on queue or stack,
waiting to be processed.
STATUS=3(Processed State): The node N has been
processed.
1 http://www.chitkara.edu.in
BREADTH-FIRST SEARCH
Uses queue to hold nodes that are waiting to be
processed
STATUS field tells the current status of each node
http://www.chitkara.edu.in
2.Put the starting node A in QUEUE and change its status to waiting
state(STATUS=2) 3.Repeat steps 4 and 5 until QUEUE is empty 4. Remove front node N of QUEUE. Process N and change the status of N to processed state(STATUS=3) 5. Add to rear of QUEUE neighbors of N that are in steady state(STATUS =1) and change their status to waiting state(STATUS=2) [End of step 3 loop] 6. Exit
3 http://www.chitkara.edu.in
Example
To find minimum path: a.) Initially add A to queue and NULL to ORIG
FRONT= 1 REAR=1
QUEUE:A ORIG:
b.) Remove front element(A) by setting FRONT:=FRONT+1 and add neighbors of A to the queue as follows:
FRONT= 2
REAR=4
4
QUEUE: A,F,C,B
ORIG: ,A,A,A
http://www.chitkara.edu.in
c.) Remove F from queue by setting FRONT:=FRONT+1 and add neighbors of F as: FRONT= 3 QUEUE:A,F,C,B,D
REAR=5
ORIG: ,A,A,A,F
(C is already there)
FRONT= 6
REAR=6
QUEUE: A,F,C,B,D,G
ORIG: ,A,A,A,F,B
FRONT= 7
REAR=7
6 http://www.chitkara.edu.in
QUEUE: A,F,C,B,D,G,E
ORIG: ,A,A,A,F,B,G
FRONT= 8
QUEUE: A,F,C,B,D,G,E,J
REAR=8
ORIG: ,A,A,A,F,B,G,E
Now stop as J is final destination and is added to QUEUE Find path P backtracking from J:
J
7
DEPTH-FIRST SEARCH
Similar to BFS, but in DFS, we use stack
http://www.chitkara.edu.in
Initialize all nodes to ready state(STATUS=1) Push Starting node A onto stack and change its status to waiting state(STATUS=2)
3. 4.
Repeat steps 4 and 5 until stack is empty Pop the top node N of STACK. Process N & change its status to processed state(STATUS=3)
5.
Push all neighbors of N that are in ready state(STATUS=1) and change their
Exit
http://www.chitkara.edu.in
Example
To find and print all nodes reachable from J:
STACK: D,E,G
d.) Pop and print G, push neighbors of G Print G STACK: D,E,C (E is already in stack) e.) Pop and print C, push all neighbors of C Print C STACK: D,E,F f.) Pop and print F, push all neighbors of F Print F STACK: D,E (D is already in stack) g.) Pop and print E, push the neighbors of E Print E STACK: D
(none of 3 neighbors of E is in ready state) h.) Pop and print D, push neighbors of D PRINT D
11 http://www.chitkara.edu.in
STACK:
J,K,G,C,F,E,D
12
http://www.chitkara.edu.in