Created
June 10, 2022 08:46
-
-
Save sychonet/a283e374c0ff9ed8719ea89d7b3e597c to your computer and use it in GitHub Desktop.
Pseudocode for BFS where we don't visit a node twice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Return the length of the shortest path between root and target node. | |
*/ | |
int BFS(Node root, Node target) { | |
Queue<Node> queue; // store all nodes which are waiting to be processed | |
Set<Node> visited; // store all the nodes that we've visited | |
int step = 0; // number of steps neeeded from root to current node | |
// initialize | |
add root to queue; | |
add root to visited; | |
// BFS | |
while (queue is not empty) { | |
// iterate the nodes which are already in the queue | |
int size = queue.size(); | |
for (int i = 0; i < size; ++i) { | |
Node cur = the first node in queue; | |
return step if cur is target; | |
for (Node next : the neighbors of cur) { | |
if (next is not in visited) { | |
add next to queue; | |
add next to visited; | |
} | |
} | |
remove the first node from queue; | |
} | |
step = step + 1; | |
} | |
return -1; // there is no path from root to target | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment