section 9 graph search algorithms. breadth-first search idea: let |n| denote a distance of node n...
TRANSCRIPT
Section 9
• Graph search algorithms
Breadth-first search
• Idea: Let |n| denote a distance of node n from the initial node. We visit nodes in order:
• All nodes n such that |n| = 1
• All nodes n such that |n| = 2
• All nodes n such that |n| = 3
• All nodes n such that |n| = 4
• All nodes n such that |n| = 5
....
BFS: Water analogy
• BFS is similar to pouring water!
• We pour the water on the first node. When there is too much water in it, the nodes adjacent to it start to fill. And so on...
BFS
Depth-first search
• Idea: We go as deep as possible.
• Visit recursively all the adjacent nodes of the source node.
DFS: Labyrinth analogy
• DFS is similar to going through labyrinth.
• We walk leaving a thread behind us. Whenever we have the choice of path, we choose the leftmost one. If we reach a dead-end or the place already marked, we go back to the first unvisited place.
DFS
BFS + DFS
• Stunning fact - we can implement both of them using the same code, changing only the underlying SequenceStructure.
BFS + DFS
• initialize toDo with the node we are starting from
while (!empty(toDo))
{
remove a node n from toDo
visit(n)
put all unvisited neighbours of
n on toDo
}
BFS + DFS
Method toDo implementation
DFS Stack
BFS Queue
Best-first search Priority queue
Best-first search
• In situation when we have a weight function f on nodes, which tells us which node to visit first.
• BFS, but visiting neighbours according to the fumction f.
• Just use priority queue!
WWW as a graph
• Nodes -
• Edges -
WWW as a graph
• Nodes - webpages
• Edges - links
WWW as a graph
• How to write a program downloading a whole web page?
WWW as a graph
• How to write a program downloading a whole web page?
• Use graph search!
• Which one?
WWW as a graph
• How to write a program downloading a whole web page?
• Use graph search!
• Which one?
• BFS!
WWW as a graph
• Interesting questions:
• What is the diameter of the graph? (probably about 20)
• What is its structure?
• What are the efficient search algorithms? - Google, Altavista
• What is a „typical” node?
• Many more...
Bus/train map as a graph
• Nodes -
• Edges -
Bus map as a graph
• Nodes - bus/train stops/stations
• Edges - there’s an edge from one node to the other if there is a bus/train, which takes you from one stop to the other.
• www.bahn.de
• How to find how to reach a bus stop/city?
Survival skills
• How to find a way out in the labyrinth?
• Optimistic version: With a thread of string.
• Pessimistic version: Without a thread.
With a thread
• Use DFS - using a thread to go back to the yet unvisited paths.
Without a thread
• A heuristics which often works - always turn left.