Breath First Searching Depth First Searching C and
Breath First Searching & Depth First Searching C and Data Structures Baojian Hua bjhua@ustc. edu. cn
Searching n n The systematic way to traverse all vertex in a graph Two general methods: n breath first searching (BFS) n n depth first searching (DFS) n n start from one vertex, first visit all the adjacency vertices eager method These slides assume the adjacency list representation
Sample Graph 1 2 3 4 5 6
“graph” ADT in C: Interface // in file “graph. h” #ifndef GRAPH_H #define GRAPH_H typedef void (*ty. Visit. Fn)(poly); typedef struct graph *graph; graph new (); void insert. Vertex (graph g, poly x); void insert. Edge (graph g, poly from, poly to); void bfs (graph g, poly start, ty. Visit. Fn visit); void dfs (graph g, poly start, ty. Visit. Fn visit); // we’d see more later … #endif
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1;
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; (choice)
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; print 4;
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; print 4; print 5;
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; print 4; print 5; print 3;
Sample Graph BFS bfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; print 4; print 5; print 3; print 6;
Moral n n n BFS is very much like the level-order traversal on trees Maintain internally a queue to control the visit order Obtain a BFS forest when finished
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1;
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; (choice)
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; (choice) print 5;
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; (choice) print 5; print 4;
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; (choice) print 5; print 4; print 3; (choice)
Sample Graph DFS dfs (g, 1, nat. Output); 1 2 3 4 5 6 print 1; print 2; (choice) print 5; print 4; print 3; (choice) print 6;
Moral n n DFS is very much like the pre-order traversal on trees Maintain internally a stack to control the visit order n n for recursion function, machine maintain the stack Obtain a DFS forest when finished
- Slides: 20