implement of DFS algorithm

133 Views Asked by At

i would like to check myself whether following procedures for DFS -Depth First search is correct( so i would like to check if i understood it correctly) we have following Graph enter image description here

we use stack for DFS, so let start : initially vertex A is added to the stack and it is marked as visited(first output is A), next adjacent element are (B,C,D), first let add B, because B has no any adjacent element pop B(so we have A B), now next visiting element of A is C, we push C on stack and C will be also output (A B C), C has only non visited element K, so add k to the stack and write on output (A B C K), K we has following non visited elements D and and L, push D(A B C K D), but D has no non visited adjacent vertex , so pop from stack , and push L, (A B C K D L), now L has only J so push J ( A B C K D L J) and J has only M so finally we have A B C K D L J M

am i right?thanks in advance

2

There are 2 best solutions below

9
On BEST ANSWER

Not sure what you said but in case you chose to discover L from node K that is incorrect. You go to node K from node D. So basically the DFS graph has the following arcs:(A,B), (A,C), (C,K), (K,D),(D,L), (L,J), (J,M).

0
On

so for breadth first algorithm we use Queue -FIFO=first in first out, first will be node A, new A has three node which is adjacent , alphabetically we push

 B 
 C 
 D, 

now current working node is B, B has no any adjacent node, so deque B ( we have A B as list),in queue we have left

C D so current working node is C and remove from queue (A B C), now C has only non visited node K so enque in queue , we have

D K now currently working node is D, we has L as an visited so enque L and remove D

( A B C D) K L now K has no any non visited so deque it ( A B C D K), now we gave L on top of queue , deque L( A B C D K L) and L has only J so enqueue J (A B C D K L J M) will be answer i think i am right