200 likes | 420 Views
Breath First Searching & Depth First Searching. C and Data Structures Baojian Hua bjhua@ustc.edu.cn. Searching. The systematic way to traverse all vertex in a graph Two general methods: breath first searching (BFS) start from one vertex, first visit all the adjacency vertices
E N D
Breath First Searching & Depth First Searching C and Data Structures Baojian Hua bjhua@ustc.edu.cn
Searching • The systematic way to traverse all vertex in a graph • Two general methods: • breath first searching (BFS) • start from one vertex, first visit all the adjacency vertices • depth first searching (DFS) • 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 (*tyVisitFn)(poly); typedef struct graph *graph; graph new (); void insertVertex (graph g, poly x); void insertEdge (graph g, poly from, poly to); void bfs (graph g, poly start, tyVisitFn visit); void dfs (graph g, poly start, tyVisitFn visit); // we’d see more later … #endif
Sample Graph BFS bfs (g, 1, natOutput); 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, natOutput); print 1; 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, natOutput); print 1; print 2; (choice) 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, natOutput); print 1; print 2; print 4; 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, natOutput); print 1; print 2; print 4; print 5; 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, natOutput); print 1; print 2; print 4; print 5; print 3; 1 2 3 4 5 6
Sample Graph BFS bfs (g, 1, natOutput); print 1; print 2; print 4; print 5; print 3; print 6; 1 2 3 4 5 6
Moral • 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, natOutput); 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, natOutput); print 1; 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, natOutput); print 1; print 2; (choice) 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; print 4; 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; print 4; print 3; (choice) 1 2 3 4 5 6
Sample Graph DFS dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; print 4; print 3; (choice) print 6; 1 2 3 4 5 6
Moral • DFS is very much like the pre-order traversal on trees • Maintain internally a stack to control the visit order • for recursion function, machine maintain the stack • Obtain a DFS forest when finished