Presentation is loading. Please wait.

Presentation is loading. Please wait.

Breath First Searching & Depth First Searching C and Data Structures Baojian Hua

Similar presentations


Presentation on theme: "Breath First Searching & Depth First Searching C and Data Structures Baojian Hua"— Presentation transcript:

1 Breath First Searching & Depth First Searching C and Data Structures Baojian Hua bjhua@ustc.edu.cn

2 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

3 Sample Graph 1 4 2 65 3

4 “ 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

5 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput);

6 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput); print 1;

7 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput); print 1; print 2; (choice)

8 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput); print 1; print 2; print 4;

9 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput); print 1; print 2; print 4; print 5;

10 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput); print 1; print 2; print 4; print 5; print 3;

11 Sample Graph BFS 1 4 2 65 3 bfs (g, 1, natOutput); print 1; print 2; print 4; print 5; print 3; print 6;

12 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

13 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput);

14 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput); print 1;

15 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput); print 1; print 2; (choice)

16 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput); print 1; print 2; (choice) print 5;

17 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; print 4;

18 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; print 4; print 3; (choice)

19 Sample Graph DFS 1 4 2 65 3 dfs (g, 1, natOutput); print 1; print 2; (choice) print 5; print 4; print 3; (choice) print 6;

20 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


Download ppt "Breath First Searching & Depth First Searching C and Data Structures Baojian Hua"

Similar presentations


Ads by Google