100 likes | 279 Views
BFS, DFS CSCI3160 tutorial (3 rd week) Office: SHB 913 Office Hour: ( Mon ) 10:00 -12:00 Email: jjye @cse.cuhk.edu.hk. Ye Junjie. Outline. BFS & DFS Implementation breadth-first search (BFS) depth-first search (DFS) Sitting Plan Problem General case. Data structures. Adjacency list
E N D
BFS, DFSCSCI3160 tutorial (3rd week)Office: SHB 913 Office Hour: (Mon) 10:00 -12:00 Email: jjye@cse.cuhk.edu.hk Ye Junjie
Outline BFS & DFS Implementation breadth-first search (BFS) depth-first search (DFS) Sitting Plan Problem General case
Data structures Adjacency list The representation of all edge in an undirected graph as a list We keep, for each vertex in the graph, a list of all other vertices which it has an edge to. Stack last-in, first-out PUSH: insert new item to stack POP: delete top item from stack Queue first-in, first-out push(), pop(), empty(), top() 1 2 3 4 5 6 7 1 2 3 4 2 1 3 5 6 3 1 2 6 4 1 6 5 2 6 2 3 4 7 7 6
Exploring graphs Input: a graph G, and a source vertex s Output: find all nodes reachable from the source BFS: choose frontier edge incident to least recently visited vertex Using a queue DFS: choose frontier edge incident to most recently visited vertex Using a stack
Example of BFS Nodes in Queue: Procedure BFS (G, s): create a queue Q push s to Q mark s while Q is not empty{ get top item v from Q, remove v find all unvisited vertices adjacent with v mark them and push themto Q } 1 2 3 4 5 6 7 Q 1 2 3 4 5 6 7
Example of DFS Nodes in Stack: Procedure DFS (G, s): create a stack S push s to S mark s while S is not empty{ get top item v from S find an unvisited vertex w adjacent with v{ mark w pushw to S } if there is no such vertex exists remove v } 1 2 3 4 7 4 6 5 6 7 5 3 2 1 S
Different Versions (DFS) Recursively: Procedure DFS (G, s): mark s while there is a frontier edge e incident on v{ let w be the other end of e DFS(G, w) } Frontier edges in Stack: Procedure DFS (G, s): create a stack S mark s push all frontier edges to S while S is not empty{ get top item e from S, remove e if e is a frontier edge{ let w be the unvisited end of e mark w push all frontier edges going out from w to S } }
Running Time of DFS Frontier edges in Stack: Procedure DFS (G, s): create a stack S mark s push all frontier edges to S while S is not empty{ get top item e from S, remove e if e is a frontier edge{ let w be the unvisited end of e mark w push all frontier edges going out from w to S } } The running time is O(n + m), where n is the number of vertices and m is the number of edges. For each edge e, we push and pop it once. For each edge e=(u,v), we examine it twice totally for u and v.
Sitting Plan Problem Use vertex to denote one person. If person and person are too near to each other, add edge . Thus the sitting problem has a solution iff there are k vertices which covers all edges (Vertex Cover).
Thank you! Q&A