Pseudo code

The pseudo code for BFS is very similar to DFS, the main difference is that in BFS we iterate over all the connected nodes first before moving out to another level looking for our target node:

INITIALIZE paths, nodes to visit (queue), visited nodes

SET start node as visited

WHILE nodes to visit exist

GET the next node to visit as current node from top of queue

IF current node is target

INITIALIZE result with target node

WHILE path retrieval not at source

EXTRACT how we got to this node

PUSH to result

FORMAT and return relationship

ELSE

LOOP over the entire graph

IF node is connected to current node

SET its path as current node

MARK node as visited

PUSH it to queue for visiting breadth wise

RETURN Null that is no result

Sounds very similar to the other example we worked on with DFS, doesn't it? That is because DFS and BFS are very similar in terms of how we approach the problem. The minor difference between the two is that we evaluate all connected nodes before spreading out one more level in BFS, whereas we select one of the connected nodes in case of DFS and then traverse it till the entire depth.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.1.220