BFS(S, G):
Initialize: queue, visited HashSet and parent HashMap
Enqueue S onto the queue and add to visited
while stack is not empty:
dequeue node curr from front of queue
if curr == G return parent map
for each of curr's neighbors, n, not in visited set:
add n to visited set
add curr as n's parent in parent map
enqueue n onto the queue
// If we get here then there's no path`
Created
January 2, 2017 04:57
-
-
Save akueisara/4541223e11a2864e2dd92b1865824f65 to your computer and use it in GitHub Desktop.
Week 3 of Coursera's Advanced Data Structures in Java
DFS(S, G):
Initialize: stack, visited HashSet and parent HashMap
Push S onto the stack and add to visited
while stack is not empty:
pop node curr from top of stack
if curr == G return parent map
for each of curr's neighbors, n, not in visited set:
add n to visited set
add curr as n's parent in parent map
push n onto the stack
// If we get here then there's no path`
DFS(S, G, visited, parents):
if S == G return;
for each of S's neighbors, n, not in visited set:
add n to visited set
add S as n's parent in parents map
DFS(n, G, visited, parents)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment