How to navigate a maze? s • Shortest route?

Download Report

Transcript How to navigate a maze? s • Shortest route?

How to navigate a maze?
• Can we go from s to t?
• Shortest route?
• How fast can we
compute this?
A first attempt
ExploreMaze(before, here)
If here != t
Let there be next reachable square
in clock-wise order after before
ExploreMaze(there, here)
A second attempt
ExploreMaze(here)
Mark here as visited
For every square there adjacent to here
If there has not been visited
ExploreMaze(there)
How to navigate a graph?
• Can we go from s to t?
• Shortest route?
• How fast can we
compute this?
DFS traversal
DFS(G)
DFS-visit(u)
counter = 0
For u in V[G]
Mark u as not visited
For u in V[G]
If u was not visited
parent[u] = nil
DFS-visit(u)
Mark u as visited
counter = counter + 1
d[u] = counter
For v adjacent to u
If v was not visited
parent[v] = u
DFS-visit(v)
counter = counter + 1
f[u] = counter
BFS traversal
Compute layers L1, L2,… such that nodes
in layer Lk are at distance k from s.
• L1: nodes reachable by one edge from s
• Li+1: nodes not in L1,…,Li reachable by
one edge from Li
BFS traversal
BFS(G,s)
For u in V[G]
Mark u as not discovered
Q = empty queue
Mark s as discovered
dist[s] = 0
parent[s] = nil
Add(Q,s)
While Q is not empty
u = RemoveFirst(Q)
For v adjacent to u
If v was not discovered
Mark v as discovered
dist[v] = dist[u] + 1
parent[v] = u
Add(Q,v)