graph_traversals bfs and dfs

Upload: rehana988

Post on 07-Apr-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Graph_traversals BFS and DFS

    1/13

    Breadth-First Search (BFS)

    Intuition: BFS(vertex v)

    To start, all vertices are unmarked.

    Startat v. Visitv and mark as visited.

    Visit every unmarked neighbour ui of v and mark each uias visited.

    Markv finished.

    Recurseon each vertex marked as visited in the order theywere visited.

    BFS of an undirected Graph

    v v

    v v

    3

    6

    5

    7

    8

    12

    3 45

    6

    12 1

    43

    2 1

    u1

    u2

    u3

    4

    49

  • 8/6/2019 Graph_traversals BFS and DFS

    2/13

    Q: Whatinformationabout the graph can aBFSbe used to find?

    the shortest path from v to any other vertex u and this distance

    Whether the graph is connected. Number of connected compon

    Q: What does theBFSconstruct?

    a BFS tree that visits every node connected to v, we call this a span

    Q: What is an appropriateADTtoimplementa BFS given anad-jacency listrepresentation of a graph? a FIFO (first in, first out) queue

    which has the operations:

    ENQUEUE(Q,v)

    DEQUEUE(Q)

    ISEMPTY(Q)

    Q: Whatinformationwill we need to store along the way?

    the current node

    the predecessor

    the distance so far from v

    50

  • 8/6/2019 Graph_traversals BFS and DFS

    3/13

    The BFS Algorithm

    We will use p[v] to represent the predecessorof v and d[v] torepresent the number of edgesfrom v (i.e., the distancefrom v).

    BFS(G=(V,E),v)

    for all vertices u in V

    color[u] := black

    d[u] := infinity; \\ we use infinity to deno

    p[u] := NIL; \\ "not connected"

    end for

    initialize an empty queue Q;

    color[v] := green;

    d[v] := 0;

    p[v] := NIL;

    ENQUEUE(Q,v);

    while not ISEMPTY(Q) do

    u := DEQUEUE(Q);

    for each edge (u,w) in E do

    if (color[w] == black) then

    color[w] := green;

    d[w] := d[u] + 1;

    p[w] := u;

    ENQUEUE(Q,w);

    end if

    end for

    color[u] := red;

    end while

    END BFS

    51

  • 8/6/2019 Graph_traversals BFS and DFS

    4/13

    Complexity of BFS(G,v)

    Q: How many times is each nodeENQUEUEed?

    at most once, when it is black, at which point it is coloured green.

    Therefore, the adjacency list of each node is examined at most

    once, so that the total running time of BFS is O(n + m)

    or linear in the size of the adjacency list.

    NOTES:

    BFS will visit only those vertices that are reachable from v.

    If the graph is connected (in the undirected case) or strongly-connected (in the directed case), then this will be all thevertices.

    If not, then we may have to call BFS on more than one startvertex in order to see the whole graph.

    Q: Prove thatd[u] really does represent thelengthof theshort-

    est path(in terms of number of edges) fromv tou.

    52

  • 8/6/2019 Graph_traversals BFS and DFS

    5/13

    Depth-First Search

    Intuition: DFS(G,v)

    All verticesand edgesstart out unmarked.

    Walk as faras possible away from v visiting vertices

    If the current vertexhas not been visited,

    Mark as visited and the edge that is traversed as a DFSedge.

    Otherwise, if the vertex has been visited,

    mark the traversed edge as a back-edge, back up to the

    previous vertex

    When the current vertex has only visited neighbours leftmark as finished (white).

    Backtrack to the first vertex that is not finished.

    Continue.

    53

  • 8/6/2019 Graph_traversals BFS and DFS

    6/13

    Example.

    Backedg

    DFSedge

    v

    v

    vv

    v

    v

    Just like BFS, DFS constructs a spanning-tree and gives con-nected component information.

    Q: Does it find the shortest path between v and all other ver-tices?

    no

    54

  • 8/6/2019 Graph_traversals BFS and DFS

    7/13

    Implementing a DFS

    Q: Which ADT would be the most helpful for implementing DFSgiven anadjacency listrepresentation ofG?

    A stack S to store edges

    with the operations

    PUSH(S, (u,v))

    POP(S)

    ISEMPTY(S)

    Q: Whatadditional data(for each vertex) should we keep in orderto easily determine whether an edge is a cross-edge or a DFS-edge?

    d[v] will indicate the discovery time

    f[v] will indicate the finish time.

    55

  • 8/6/2019 Graph_traversals BFS and DFS

    8/13

    Algorithm DFS(G,s)

    DFS(G=(V,E),s)for all vertices v in V

    color[v] := black;

    d[v] := infinity;

    f[v] := infinity;

    p[v] := NIL;

    end for

    initialize an empty stack S;

    color[s] := green; d[s] := 0; p[s] := NIL;

    time := 0;

    PUSH(S,(s,NIL));

    for each edge (s,v) in E do

    PUSH(S,(s,v));

    end for

    while not ISEMPTY(S) do

    (u,v) := POP(S);

    if (v == NIL) then // Done with u

    time := time + 1;

    f[u] := time;

    color[u] := white;end if

    else if (color[v] == black) then

    color[v] := green;

    time := time + 1;

    d[v] := time;

    p[v] := u;

    PUSH(S,(v,NIL)); // Marks the end of vs neighbor

    for each edge (v,w) in E do

    PUSH(S,(v,w));

    end for

    (*) end if

    end while

    END DFS

    56

  • 8/6/2019 Graph_traversals BFS and DFS

    9/13

    Complexity of DFS(G,s)

    Q: How many times doesDFSvisit theneighboursof anode?

    once...when the node is green and the neighbour is black

    Therefore, the adjacency list of each vertex is visited atmost once.

    So the total running timeis just like for BFS,(n+m) i.e.,linear in the size of the adjacency list.

    Note that the gold edges, or the DFS edges form a tree calledthe DFS-tree.

    Q: Is the DFS treeunique for a given graph G starting at s? no

    For certain applications, we need to distinguish between differenttypes of edges in E:

    57

  • 8/6/2019 Graph_traversals BFS and DFS

    10/13

    We can specify edges on DFS-tree according to how they aretraversedduring the search.

    Tree-Edges are the edges in the DFS tree.

    Back-Edges are edges from a vertex u to an ancestor of uin the DFS tree.

    Forward-Edges are edges from a vertex u to a descen-

    dent of u in the DFS tree.

    Cross-Edges are all the other edges that are not part ofthe DFS tree (from a vertex u to another vertex v that isneither an ancestor nor a descendent of u in the DFS tree).

    Q: Whichvariablefacilitatesdistinguishingbetween these edges?

    p[v]

    Q: How can aDFSbe used todeterminewhether a graphG hasanycycles?

    (Note: A cycle is a path from a vertex u to itself.)

    It is not hard to see that there is a cycle in G if and only if there are

    Q: How can we detectcross-edgesduring a DFS?

    Add a test after the line marked by (*) in DFS. If the color of v is gree

    58

  • 8/6/2019 Graph_traversals BFS and DFS

    11/13

    Minimum Cost Spanning Trees (MCSTs)

    Let G = (V,E) be a connected, undirected graph withedge weightsw(e) for each edge e E.

    A treeis a subset of edges A Esuch that A is connectedand does not contain a cycle.

    Thick edges are in A, the thin ones are not. The first one is a

    tree and the other two are not.

    Not a tree (not connectNot a tree (has a cycle)Tree

    A spanning tree is a tree A such that every vertexv V is anendpointof at least one edge in A.

    59

  • 8/6/2019 Graph_traversals BFS and DFS

    12/13

    Q: How many edgesmust any spanning treecontain?

    n 1 edges where |V| = n

    How would you prove this is true? (proof by induction on n).

    Q: What algorithms have we seen to construct aspanning tree?

    DFS, BFS

    A minimum cost spanning tree(MCST) is a spanning tree A suchthat the sum of the weights is minimizedfor all possible spanningtrees B.

    Formally:

    w(A) =

    eA

    w(e) w(B)

    for all other spanning trees B.

    Minimum Cost Spanning Tree

    6

    5

    48

    2

    Spanning tree, but not minimum cost

    6

    5

    48

    2

    3 3

    3

    Two different MCSTs on the same graph

    3 3

    3

    60

  • 8/6/2019 Graph_traversals BFS and DFS

    13/13

    Q: What is an example of an application in which you would we

    want to be able to find a MCST?

    A: Imagine you have a network of computers that are connected by various links.

    We will look at two algorithms for constructing MCSTs. The firstis Prims Algorithm.

    Prims Algorithm

    Prims algorithmuses a Priority Queue ADT.

    A priority queue is just like a queue except that every item in thequeuehas a priority (usually just a number).

    More formally, a priority queueconsists of

    a set of elements

    each element has a priority

    The operations:

    ENQUEUE(x,p): insert an element x in the set, with priority

    ISEMPTY(): return whether the priority queue is empty

    EXTRACT MIN(): remove and return an element x with the

    61