Skip to content

Instantly share code, notes, and snippets.

@tamarous
Created March 29, 2018 12:19
Show Gist options
  • Save tamarous/f1b6ae45e0564c55bc5ffc6918f864cf to your computer and use it in GitHub Desktop.
Save tamarous/f1b6ae45e0564c55bc5ffc6918f864cf to your computer and use it in GitHub Desktop.
Pseudo-code for DFS and BFS.
// DFS
void search(Node root) {
if (root == NULL) {
return;
}
visit(root);
root.visited = true;
foreach (Node n in root.adjacent) {
if (n.visited = false) {
search(n);
}
}
}
// BFS
void search(Node root) {
Queue queue = new Queue();
root.visited = true;
visit(root);
queue.enqueue(root);
while(! queue.empty()) {
Node r = queue.dequeue();
foreach(Node n in r.adjacent) {
if (n.visited == false) {
visit(n);
n.visited = true;
queue.enqueue(n);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment