370 likes | 465 Views
Search Related Algorithms. DFS vs BFS. BFS - Spreads out in all directions. DFS vs BFS. BFS - Spreads out in all directions 1 Hop. DFS vs BFS. BFS - Spreads out in all directions 1 Hop 2 Hops. DFS vs BFS. BFS - Spreads out in all directions 1 Hop 2 Hops 3 Hops.
E N D
DFS vs BFS • BFS - Spreads out in all directions
DFS vs BFS • BFS - Spreads out in all directions • 1 Hop
DFS vs BFS • BFS - Spreads out in all directions • 1 Hop • 2 Hops
DFS vs BFS • BFS - Spreads out in all directions • 1 Hop • 2 Hops • 3 Hops
DFS vs BFS • BFS - Spreads out in all directions • 1 Hop • 2 Hops • 3 Hops • 4 Hops
BFS • BFS : Breadth First Search Put starting vertex on queue Build visited array Mark first visited While queue is not empty current = queue.dequeue() For each neighbor If( !Visited[neighbor] ) mark neighbor visitedenqueue neighbor bool array1 = visited, 0 = not visitedvisited seen List of intsvertices to visit "Visit" as we add to queue. Nothing should be duplicated on queue
BFS • Finds shortest path to all connected vertices • Space • Exponential in search depth • Degree of 100 for each vertex • First hop – 100 vertices on queue • Second hop - ~100^2 vertices on queue • Third hop - ~100^3 vertices to track • But limited by number of vertices : O(V)
BFS Application • Bipartite : can divide graph into two sets of vertices A, B; every edge connects an element of A to element of B
BFS Application • Storage array for color • Mark start vertex blue • When visiting a node, color neighbors opposite color • Conflict = not bipartite
BFS Application • Storage array for color • Mark start vertex blue • When visiting a node, color neighbors opposite color • Conflict = not bipartite
BFS Application • Storage array for color • Mark start vertex blue • When visiting a node, color neighbors oppositecolor • Conflict = not bipartite
BFS Application • Storage array for color • Mark start vertex blue • When visiting a node, color neighbors oppositecolor • Conflict = not bipartite
Getting Back a Tree • To recover search tree, build list of parent vertices
Getting Back a Tree • Parent vertices equivalent to pointers in an upside down tree
Getting Back a Tree • Parent vertices equivalent to pointers in an upside down tree • Root only visited nodewithout parent • Find path from any vertexto root in O(V)
Tree Search Result • Info to reconstruct search tree • root • list of parents • list containing order vertices visited
Tree Search Result • BFS returns Tree • searchOrderslist of verticesorder explored • parentused as arrayto record indexof parent ofeach vertexin tree
Tree Search Result • DFS does same • SearchOrders &Parent parametersto recursive helper
DFS vs BFS • DFS - from 8Chain in one direction(smallest index neighbor explored first)
DFS vs BFS • DFS - from 8Chain in one direction(smallest index neighbor explored first) • Backtrack when stuck • Chain again as soon asa new path available
DFS vs BFS • DFS - from 8Chain in one direction(smallest index neighbor explored first) • Backtrack when stuck • Chain again as soon asa new path available
DFS vs BFS • DFS - from 8Chain in one direction(smallest index neighbor explored first) • Backtrack when stuck • Chain again as soon asa new path available
DFS vs BFS • DFS - from 8Chain in one direction(smallest index neighbor explored first) • Backtrack when stuck • Chain again as soon asa new path available
DFS • DFS : Depth First Search Put starting vertex on stack Build visited array While stack is not empty Current = stack.pop()if current is not visited mark current visited For each neighbor if neighbor not visited push neighbor on stack Need to allow for duplicates on stack "Visit" when actually processed
DFS • DFS : Depth First Search - Recursive • Build visited array • Call helper with startVertex and visitedArray Helper(startVertex, visitedArray) if(startVertex is visted) return visitedArray[startVertex] = visited For each neighbor of startVertex Helper(startVertex, vistedArray)
DFS • Finds all connected vertices • Space • Proportional to length of current path O(V) • Recursive version implicitly stores on call stack • Iterative version explicitly stores on stack • May have dupes
DFS vs BFS • Both worst case O(V) space • BFS gets there in fewer hops • Time : • Adjacency list O(V + E) • Build visited list : V • Check every edge : E • Adjacency Matrix O(V2) • For each vertex, check every other • Pick based on pattern • BFS for shortest path, bipartite coloring, etc… • DFS for long paths…
DAG • DAGs : Directed Acyclical Graphs • Common in scheduling type problems
Cycle Detection • To detect cycle • Do DFS from each node until all are visited • If a neighbor to current is already on stack we have a cycle
Detect Cycles • Detect a cycle in a DAG :DFS – watch out for values already on stack boolcheckCycle()Make boolisVisited[] – every vertex to falseMake boolinStack[] – every vertex to falseFor each vertex If not already visitedif cycleDFS(vertex, isVisited, inStack) return truereturn false boolcycleDFS(vertex, isVisited, inStack) mark vertex inStack mark vertex visited for each neighbor if in stack return true //cycle!! if not visited if cycleDFS(neighbor, isVisited, inStack) return true //found a cycle down streammark vertex not inStack return false //guess we were OK along this path
Topological Sort • Topological Sort : turn DAG into ordered list such that all edges point one way • Maybe multiple orderings
Topological Sort • Topological SortWith DFS : add as you LEAVE Make list orderingMake boolisVisited[] – every vertex to falseFor each vertex If not visited, do topoDFS(vertex, isVisited, ordering) topoDFS(vertex, isVisited, ordering) mark vertex visited for each neighbor if not visitedtopoDFS(neighbor, isVisited, ordering)add vertex to front of ordering
Connected Components • Connected components :Break graph up intro strongly connected groups
Connected Components • Connected components : • Phase 1 • Do DFSs until each vertex visited • Record time each vertex left the stack (last visited) • Phase 2 • Sort list of vertexes based on last visit time (large to small) • Reverse all the edges • Do DFS from each node based on sorted listStarts at most distant nodes, checks for back connections
Connected Components • Connected components – part 1 Make intlastVisitTime[]int time = 0Make boolisVisited[] – every vertex to falseFor each vertex If not visited, do connectDFS(vertex, isVisited, lastVisit, time) connectDFS(vertex, isVisited, lastVisit, &time) mark vertex visitedtime++ for each neighbor if not visitedconnectDFS(neighbor, isVisited, lastVisit, time)lastVisit[vertex] = ++time
Connected Components • Connected components – part 2 Make masterlist of vertices – sorted based on lastVisitTimeReverse all edgesMake boolisVisited[] – every vertex to falseFor each vertex in listIf not visited, Make curConnected list do connect2DFS(vertex, isVisited, curConnected)print curConnected connect2DFS(vertex, isVisited, curConnected) mark vertex visited add to curConnected for each neighbor if not visitedconnect2DFS(neighbor, isVisited, ccurConnected)