SlideShare uma empresa Scribd logo
1 de 143
Baixar para ler offline
Graphs




       League of Programmers
              ACA, IIT Kanpur




League of Programmers   Graphs
Outline




          League of Programmers   Graphs
Basics




  What are Graphs?




                League of Programmers   Graphs
Basics




  What are Graphs?
     An abstract way of representing connectivity using nodes (or
     vertices) and edges




                 League of Programmers   Graphs
Basics




  What are Graphs?
     An abstract way of representing connectivity using nodes (or
     vertices) and edges
     Graph G=(V,E) , E ⊆ V ∗ V




                 League of Programmers   Graphs
Basics




  What are Graphs?
     An abstract way of representing connectivity using nodes (or
     vertices) and edges
     Graph G=(V,E) , E ⊆ V ∗ V
     We will label the nodes from 1 to n (V)




                 League of Programmers   Graphs
Basics




  What are Graphs?
     An abstract way of representing connectivity using nodes (or
     vertices) and edges
     Graph G=(V,E) , E ⊆ V ∗ V
     We will label the nodes from 1 to n (V)
     m edges connect some pairs of nodes (E)




                 League of Programmers   Graphs
Basics




  What are Graphs?
     An abstract way of representing connectivity using nodes (or
     vertices) and edges
     Graph G=(V,E) , E ⊆ V ∗ V
     We will label the nodes from 1 to n (V)
     m edges connect some pairs of nodes (E)
     Edges can be either one-directional (directed) or bidirectional




                  League of Programmers   Graphs
Basics




  What are Graphs?
     An abstract way of representing connectivity using nodes (or
     vertices) and edges
     Graph G=(V,E) , E ⊆ V ∗ V
     We will label the nodes from 1 to n (V)
     m edges connect some pairs of nodes (E)
     Edges can be either one-directional (directed) or bidirectional
     Nodes and edges can have some auxiliary information




                  League of Programmers   Graphs
Basics




  Terminologies




                  League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph




                 League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph
      Adjacency(u) = {v |(u , v ) ∈ E }




                  League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph
      Adjacency(u) = {v |(u , v ) ∈ E }
      Degree(u) = |Adjacency(u)|




                  League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph
      Adjacency(u) = {v |(u , v ) ∈ E }
      Degree(u) = |Adjacency(u)|
      Subgraph: A subset of vertices and edges is a subgraph




                 League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph
      Adjacency(u) = {v |(u , v ) ∈ E }
      Degree(u) = |Adjacency(u)|
      Subgraph: A subset of vertices and edges is a subgraph
      Walk: A sequence v , v , . . . , v such that (v , v + ) ∈ E
                             1    2        k         i   i   1




                  League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph
      Adjacency(u) = {v |(u , v ) ∈ E }
      Degree(u) = |Adjacency(u)|
      Subgraph: A subset of vertices and edges is a subgraph
      Walk: A sequence v , v , . . . , v such that (v , v + ) ∈ E
                             1    2        k         i   i   1


      Trial: A trial is a walk in which no edge occurs twice




                  League of Programmers   Graphs
Basics




  Terminologies
      Vertex: node of a graph
      Adjacency(u) = {v |(u , v ) ∈ E }
      Degree(u) = |Adjacency(u)|
      Subgraph: A subset of vertices and edges is a subgraph
      Walk: A sequence v , v , . . . , v such that (v , v + ) ∈ E
                            1    2        k       i   i   1


      Trial: A trial is a walk in which no edge occurs twice
      Closed path: A walk where starting and ending vertex are the
      same




                 League of Programmers   Graphs
Basics




  Storing Graphs




                   League of Programmers   Graphs
Basics




  Storing Graphs
       We need to store both the set of nodes V and the set of edges
       E




                  League of Programmers   Graphs
Basics




  Storing Graphs
       We need to store both the set of nodes V and the set of edges
       E
       Nodes can be stored in an array. Edges must be stored in
       some other way.




                  League of Programmers   Graphs
Basics




  Storing Graphs
       We need to store both the set of nodes V and the set of edges
       E
       Nodes can be stored in an array. Edges must be stored in
       some other way.
       We want to support the following operations




                  League of Programmers   Graphs
Basics




  Storing Graphs
       We need to store both the set of nodes V and the set of edges
       E
       Nodes can be stored in an array. Edges must be stored in
       some other way.
       We want to support the following operations
           Retrieving all edges incident to a particular node




                  League of Programmers   Graphs
Basics




  Storing Graphs
       We need to store both the set of nodes V and the set of edges
       E
       Nodes can be stored in an array. Edges must be stored in
       some other way.
       We want to support the following operations
           Retrieving all edges incident to a particular node
           Testing if given two nodes are directly connected




                  League of Programmers   Graphs
Basics




  Adjacency Matrix




                 League of Programmers   Graphs
Basics




  Adjacency Matrix
      An easy way to store connectivity information




                 League of Programmers   Graphs
Basics




  Adjacency Matrix
      An easy way to store connectivity information
      Checking if two nodes are directly connected: O(1) time




                 League of Programmers   Graphs
Basics




  Adjacency Matrix
      An easy way to store connectivity information
      Checking if two nodes are directly connected: O(1) time
      Make an n x n matrix A




                 League of Programmers   Graphs
Basics




  Adjacency Matrix
      An easy way to store connectivity information
      Checking if two nodes are directly connected: O(1) time
      Make an n x n matrix A
      a[i][j] = 1 if there is an edge from i to j




                 League of Programmers   Graphs
Basics




  Adjacency Matrix
      An easy way to store connectivity information
      Checking if two nodes are directly connected: O(1) time
      Make an n x n matrix A
      a[i][j] = 1 if there is an edge from i to j
      a[i][j] = 0 otherwise




                 League of Programmers   Graphs
Basics




  Adjacency Matrix
      An easy way to store connectivity information
      Checking if two nodes are directly connected: O(1) time
      Make an n x n matrix A
      a[i][j] = 1 if there is an edge from i to j
      a[i][j] = 0 otherwise
      Uses O(n ) memory. So, use when n is less than a few
               2


      thousands, AND when the graph is dense




                   League of Programmers   Graphs
Basics




  Adjacency List




                   League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.




                  League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.
      Lists have variable lengths




                  League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.
      Lists have variable lengths
      We can use: vector< vector<int> >




                  League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.
      Lists have variable lengths
      We can use: vector< vector<int> >
      Space usage: O(n + m)




                  League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.
      Lists have variable lengths
      We can use: vector< vector<int> >
      Space usage: O(n + m)
      Checking if edge (Vi,Vj) is present in G:




                  League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.
      Lists have variable lengths
      We can use: vector< vector<int> >
      Space usage: O(n + m)
      Checking if edge (Vi,Vj) is present in G:




                  League of Programmers   Graphs
Basics




  Adjacency List
      Each vertex maintains a list of vertices that are adjacent to it.
      Lists have variable lengths
      We can use: vector< vector<int> >
      Space usage: O(n + m)
      Checking if edge (Vi,Vj) is present in G:
      O(min(deg(Vi),deg(Vj)))




                  League of Programmers   Graphs
Basics




  Special Graphs




                   League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.




                    League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.
         Tree: a connected acyclic graph
         The most important type of graph in CS
         Alternate denitions (all are equivalent!)




                    League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.
         Tree: a connected acyclic graph
         The most important type of graph in CS
         Alternate denitions (all are equivalent!)
             connected graph with n-1 edges




                    League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.
         Tree: a connected acyclic graph
         The most important type of graph in CS
         Alternate denitions (all are equivalent!)
             connected graph with n-1 edges
             An acyclic graph with n-1 edges




                    League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.
         Tree: a connected acyclic graph
         The most important type of graph in CS
         Alternate denitions (all are equivalent!)
             connected graph with n-1 edges
             An acyclic graph with n-1 edges
             There is exactly one path between every pair of nodes




                    League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.
         Tree: a connected acyclic graph
         The most important type of graph in CS
         Alternate denitions (all are equivalent!)
             connected graph with n-1 edges
             An acyclic graph with n-1 edges
             There is exactly one path between every pair of nodes
             An acyclic graph but adding any edge results in a cycle




                    League of Programmers   Graphs
Basics




  Special Graphs
         Implicit graphs
         Two squares on an 8x8 chessboard. Determine the shortest
         sequence of knight moves from one square to the other.
         Tree: a connected acyclic graph
         The most important type of graph in CS
         Alternate denitions (all are equivalent!)
             connected graph with n-1 edges
             An acyclic graph with n-1 edges
             There is exactly one path between every pair of nodes
             An acyclic graph but adding any edge results in a cycle
             A connected graph but removing any edge disconnects it




                    League of Programmers   Graphs
Basics




  Special Graphs




                   League of Programmers   Graphs
Basics




  Special Graphs
         Directed Acyclic Graph (DAG)




                   League of Programmers   Graphs
Basics




  Special Graphs
         Directed Acyclic Graph (DAG)
         Bipartite Graph
         Nodes can be separated into two groups S and T such that edges
         exist between S and T only (no edges within S or within T)




                    League of Programmers   Graphs
Outline




          League of Programmers   Graphs
Traversal




  Graph Traversal




                    League of Programmers   Graphs
Traversal




  Graph Traversal
      The most basic graph algorithm that visits nodes of a graph in
      certain order




                  League of Programmers   Graphs
Traversal




  Graph Traversal
      The most basic graph algorithm that visits nodes of a graph in
      certain order
      Used as a subroutine in many other algorithms




                  League of Programmers   Graphs
Traversal




  Graph Traversal
      The most basic graph algorithm that visits nodes of a graph in
      certain order
      Used as a subroutine in many other algorithms
      We will cover two algorithms




                  League of Programmers   Graphs
Traversal




  Graph Traversal
      The most basic graph algorithm that visits nodes of a graph in
      certain order
      Used as a subroutine in many other algorithms
      We will cover two algorithms
            Depth-First Search (DFS): uses recursion




                   League of Programmers   Graphs
Traversal




  Graph Traversal
      The most basic graph algorithm that visits nodes of a graph in
      certain order
      Used as a subroutine in many other algorithms
      We will cover two algorithms
            Depth-First Search (DFS): uses recursion
            Breadth-First Search (BFS): uses queue




                   League of Programmers   Graphs
Traversal




  DFS




            League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)
        Use non-recursive version if recursion depth is too big (over a
        few thousands)




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)
        Use non-recursive version if recursion depth is too big (over a
        few thousands)
        Replace recursive calls with a stack




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)
        Use non-recursive version if recursion depth is too big (over a
        few thousands)
        Replace recursive calls with a stack
        Complexity




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)
        Use non-recursive version if recursion depth is too big (over a
        few thousands)
        Replace recursive calls with a stack
        Complexity




                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)
        Use non-recursive version if recursion depth is too big (over a
        few thousands)
        Replace recursive calls with a stack
        Complexity
          Time: O(|V|+|E|)



                   League of Programmers   Graphs
Traversal




  DFS
        DFS(v): visits all the nodes reachable from v in depth-rst
        order
            Mark v as visited
            For each edge v → u :
               If u is not visited, call DFS(u)
        Use non-recursive version if recursion depth is too big (over a
        few thousands)
        Replace recursive calls with a stack
        Complexity
          Time: O(|V|+|E|)
          Space: O(|V|) [to maintain the vertices visited till now]


                   League of Programmers   Graphs
Traversal




  DFS: Uses




              League of Programmers   Graphs
Traversal




  DFS: Uses
      Biconnected components




                League of Programmers   Graphs
Traversal




  DFS: Uses
      Biconnected components
      A node in a connected graph is called an articulation point if
      the deletion of that node disconnects the graph.




                  League of Programmers   Graphs
Traversal




  DFS: Uses
      Biconnected components
      A node in a connected graph is called an articulation point if
      the deletion of that node disconnects the graph.
      A connected graph is called biconnected if it has no
      articulation points. That is, the deletion of any single node
      leaves the graph connected.




                  League of Programmers   Graphs
Traversal




  BFS
  BFS(v): visits all the nodes reachable from v in breadth-rst order




                  League of Programmers   Graphs
Traversal




  BFS
  BFS(v): visits all the nodes reachable from v in breadth-rst order
      Initialize a queue Q




                  League of Programmers   Graphs
Traversal




  BFS
  BFS(v): visits all the nodes reachable from v in breadth-rst order
      Initialize a queue Q
      Mark v as visited and push it to Q




                  League of Programmers   Graphs
Traversal




  BFS
  BFS(v): visits all the nodes reachable from v in breadth-rst order
      Initialize a queue Q
      Mark v as visited and push it to Q
      While Q is not empty:
         Take the front element of Q and call it w
         For each edge w → u :
            If u is not visited, mark it as visited and push it to Q




                  League of Programmers   Graphs
Traversal




  BFS
  BFS(v): visits all the nodes reachable from v in breadth-rst order
      Initialize a queue Q
      Mark v as visited and push it to Q
      While Q is not empty:
         Take the front element of Q and call it w
         For each edge w → u :
            If u is not visited, mark it as visited and push it to Q
      Same Time and Space Complexity as DFS




                  League of Programmers   Graphs
Traversal




  BFS: Uses




              League of Programmers   Graphs
Traversal




  BFS: Uses
      Finding a Path with Minimum Number of edges from starting
      vertex to any other vertex.




                 League of Programmers   Graphs
Traversal




  BFS: Uses
      Finding a Path with Minimum Number of edges from starting
      vertex to any other vertex.
      Solve Shortest Path problem in unweighted graphs




                 League of Programmers   Graphs
Traversal




  BFS: Uses
      Finding a Path with Minimum Number of edges from starting
      vertex to any other vertex.
      Solve Shortest Path problem in unweighted graphs
      Spoj Problem
      http://www.spoj.pl/problems/PPATH/




                 League of Programmers   Graphs
Topological Sort




               League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E




                League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E
      Output: an ordering of nodes such that for each edge u → v ,
      u comes before v. There can be many answers




                 League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E
      Output: an ordering of nodes such that for each edge u → v ,
      u comes before v. There can be many answers
      Pseudocode




                 League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E
      Output: an ordering of nodes such that for each edge u → v ,
      u comes before v. There can be many answers
      Pseudocode
          Precompute the number of incoming edges deg(v) for each
          node v




                 League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E
      Output: an ordering of nodes such that for each edge u → v ,
      u comes before v. There can be many answers
      Pseudocode
          Precompute the number of incoming edges deg(v) for each
          node v
          Put all nodes with zero degree into a queue Q




                 League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E
      Output: an ordering of nodes such that for each edge u → v ,
      u comes before v. There can be many answers
      Pseudocode
          Precompute the number of incoming edges deg(v) for each
          node v
          Put all nodes with zero degree into a queue Q
          Repeat until Q becomes empty:
            Take v from Q
            For each edge v → u
              Decrement deg(u) (essentially removing the edge v → u )
              If deg u becomes zero, push u to Q




                 League of Programmers   Graphs
Topological Sort




      Input: a DAG G = V, E
      Output: an ordering of nodes such that for each edge u → v ,
      u comes before v. There can be many answers
      Pseudocode
          Precompute the number of incoming edges deg(v) for each
          node v
          Put all nodes with zero degree into a queue Q
          Repeat until Q becomes empty:
            Take v from Q
            For each edge v → u
              Decrement deg(u) (essentially removing the edge v → u )
              If deg u becomes zero, push u to Q
      Time complexity: O (n + m)


                 League of Programmers   Graphs
Outline




          League of Programmers   Graphs
Minimum Spanning Tree




             League of Programmers   Graphs
Minimum Spanning Tree




     Input: An undirected weighted graph G = V, E




               League of Programmers   Graphs
Minimum Spanning Tree




     Input: An undirected weighted graph G = V, E
     Output: A subset of E with the minimum total weight that
     connects all the nodes into a tree




                League of Programmers   Graphs
Minimum Spanning Tree




     Input: An undirected weighted graph G = V, E
     Output: A subset of E with the minimum total weight that
     connects all the nodes into a tree
     There are two algorithms:




                League of Programmers   Graphs
Minimum Spanning Tree




     Input: An undirected weighted graph G = V, E
     Output: A subset of E with the minimum total weight that
     connects all the nodes into a tree
     There are two algorithms:
         Kruskal's algorithm




                League of Programmers   Graphs
Minimum Spanning Tree




     Input: An undirected weighted graph G = V, E
     Output: A subset of E with the minimum total weight that
     connects all the nodes into a tree
     There are two algorithms:
         Kruskal's algorithm
         Prim's algorithm




                League of Programmers   Graphs
Kruskal's Algorithm




               League of Programmers   Graphs
Kruskal's Algorithm




      Main idea: the edge e with the smallest weight has to be in
      the MST




                 League of Programmers   Graphs
Kruskal's Algorithm




      Main idea: the edge e with the smallest weight has to be in
      the MST
      Keep dierent supernodes, which are local MST's and then
      join them by adding edges to form the MST for the whole
      graph




                 League of Programmers   Graphs
Kruskal's Algorithm




      Main idea: the edge e with the smallest weight has to be in
      the MST
      Keep dierent supernodes, which are local MST's and then
      join them by adding edges to form the MST for the whole
      graph
      Pseudocode:
        Sort the edges in increasing order of weight
        Repeat until there is one supernode left:
          Take the minimum weight edge e*
          If e* connects two different supernodes:
            Connect them and merge the supernodes
          Otherwise,
            ignore e*


                 League of Programmers   Graphs
Prim's Algorithm




  Prim's Algo
  Reading Homework




               League of Programmers   Graphs
Outline




          League of Programmers   Graphs
Floyd-Warshall Algorithm




              League of Programmers   Graphs
Floyd-Warshall Algorithm




      All pair shortest distance




                  League of Programmers   Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                  3




                  League of Programmers   Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                  3



      Algorithm




                  League of Programmers   Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes




                  League of Programmers   Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes
                f(i, j, n) is the shortest distance from i to j




                  League of Programmers    Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes
                f(i, j, n) is the shortest distance from i to j
                f(i, j, 0) = cost(i, j)




                  League of Programmers    Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes
                f(i, j, n) is the shortest distance from i to j
                f(i, j, 0) = cost(i, j)

           The optimal path for f i, j, k may or may not have k as an
           intermediate node




                  League of Programmers    Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes
                f(i, j, n) is the shortest distance from i to j
                f(i, j, 0) = cost(i, j)

           The optimal path for f i, j, k may or may not have k as an
           intermediate node
                If it does, f (i, j, k) = f (i,k k-1) + f(k, j, k-1)




                  League of Programmers     Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes
                f(i, j, n) is the shortest distance from i to j
                f(i, j, 0) = cost(i, j)

           The optimal path for f i, j, k may or may not have k as an
           intermediate node
                If it does, f (i, j, k) = f (i,k k-1) + f(k, j, k-1)
                Otherwise, f (i, j, k) = f (i, j, k-1)




                  League of Programmers     Graphs
Floyd-Warshall Algorithm




      All pair shortest distance
      Runs in O(n ) time
                   3



      Algorithm
           Dene f(i, j, k) as the shortest distance from i to j, using 1 ...
           k as intermediate nodes
                f(i, j, n) is the shortest distance from i to j
                f(i, j, 0) = cost(i, j)

           The optimal path for f i, j, k may or may not have k as an
           intermediate node
                If it does, f (i, j, k) = f (i,k k-1) + f(k, j, k-1)
                Otherwise, f (i, j, k) = f (i, j, k-1)

           Therefore, f (i, j, k) is the minimum of the two quantities
           above


                  League of Programmers     Graphs
Floyd-Warshall Algorithm




              League of Programmers   Graphs
Floyd-Warshall Algorithm




      Pseudocode:
        Initialize D to the given cost matrix
        For k = 1 ...n:
        For all i and j:
          d = min{d , d + d }
           ij          ij   ik     kj




                League of Programmers   Graphs
Floyd-Warshall Algorithm




      Pseudocode:
        Initialize D to the given cost matrix
        For k = 1 ...n:
        For all i and j:
          d = min{d , d + d }
            ij          ij   ik     kj


      Can also be used to detect negative weight cycles in graph?




                 League of Programmers   Graphs
Floyd-Warshall Algorithm




      Pseudocode:
        Initialize D to the given cost matrix
        For k = 1 ...n:
        For all i and j:
          d = min{d , d + d }
            ij          ij   ik     kj


      Can also be used to detect negative weight cycles in graph?




                 League of Programmers   Graphs
Floyd-Warshall Algorithm




      Pseudocode:
        Initialize D to the given cost matrix
        For k = 1 ...n:
        For all i and j:
          d = min{d , d + d }
            ij          ij   ik     kj


      Can also be used to detect negative weight cycles in graph?
      How?




                 League of Programmers   Graphs
Floyd-Warshall Algorithm




      Pseudocode:
        Initialize D to the given cost matrix
        For k = 1 ...n:
        For all i and j:
          d = min{d , d + d }
              ij               ij   ik     kj


      Can also be used to detect negative weight cycles in graph?
      How?
      If d + d  0 for some i and j, then the graph has a negative
         ij        ji

      weight cycle




                        League of Programmers   Graphs
Dijkstra's Algorithm




               League of Programmers   Graphs
Dijkstra's Algorithm




      Used to solve Single source Shortest Path problem in
      Weighted Graphs




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Used to solve Single source Shortest Path problem in
      Weighted Graphs
      Only for Graphs with positive edge weights.




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Used to solve Single source Shortest Path problem in
      Weighted Graphs
      Only for Graphs with positive edge weights.
      The algorithm nds the path with lowest cost (i.e. the shortest
      path) between that source vertex and every other vertex




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Used to solve Single source Shortest Path problem in
      Weighted Graphs
      Only for Graphs with positive edge weights.
      The algorithm nds the path with lowest cost (i.e. the shortest
      path) between that source vertex and every other vertex
      Greedy strategy




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Used to solve Single source Shortest Path problem in
      Weighted Graphs
      Only for Graphs with positive edge weights.
      The algorithm nds the path with lowest cost (i.e. the shortest
      path) between that source vertex and every other vertex
      Greedy strategy
      Idea: Find the closest node to s, and then the second closest
      one, then the third, etc




                 League of Programmers   Graphs
Dijkstra's Algorithm




               League of Programmers   Graphs
Dijkstra's Algorithm




      Pseudo code:




                League of Programmers   Graphs
Dijkstra's Algorithm




      Pseudo code:
          Maintain a set of nodes S, the shortest distances to which are
          decided




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Pseudo code:
          Maintain a set of nodes S, the shortest distances to which are
          decided
          Also maintain a vector d, the shortest distance estimate from s




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Pseudo code:
          Maintain a set of nodes S, the shortest distances to which are
          decided
          Also maintain a vector d, the shortest distance estimate from s
          Initially, S = s, and dv = cost(s, v)




                 League of Programmers   Graphs
Dijkstra's Algorithm




      Pseudo code:
          Maintain a set of nodes S, the shortest distances to which are
          decided
          Also maintain a vector d, the shortest distance estimate from s
          Initially, S = s, and dv = cost(s, v)
          Repeat until S = V:
             Find v ∈ S with the smallest dv , and add it to S
                      /
             For each edge v → u of cost c:
                du = min{du , dv + c }




                 League of Programmers   Graphs
Dijkstra's Algorithm




               League of Programmers   Graphs
Dijkstra's Algorithm




      Time complexity depends on the implementation:
        Can be O(n + m), O(m log n), O(n log n)
                   2




                League of Programmers   Graphs
Dijkstra's Algorithm




      Time complexity depends on the implementation:
        Can be O(n + m), O(m log n), O(n log n)
                   2



      Use priority_queuenode for implementing Dijkstra's




                League of Programmers   Graphs
Dijkstra's Algorithm




      Time complexity depends on the implementation:
        Can be O(n + m), O(m log n), O(n log n)
                   2



      Use priority_queuenode for implementing Dijkstra's
      SPOJ Problem
      http://www.spoj.pl/problems/CHICAGO




                League of Programmers   Graphs
Bellman-Ford Algorithm




              League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights




                League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights
     Can also be used to detect negative weight cycles




                League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights
     Can also be used to detect negative weight cycles
     Pseudo code:




                League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights
     Can also be used to detect negative weight cycles
     Pseudo code:
         Initialize ds = 0 and dv = ∞ ∀v = s




                League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights
     Can also be used to detect negative weight cycles
     Pseudo code:
         Initialize ds = 0 and dv = ∞ ∀v = s
         For k = 1 . . . n-1:




                League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights
     Can also be used to detect negative weight cycles
     Pseudo code:
         Initialize ds = 0 and dv = ∞ ∀v = s
         For k = 1 . . . n-1:
         For each edge u → v of cost c:
            dv = min{dv , du + c }




                League of Programmers   Graphs
Bellman-Ford Algorithm




     Single source shortest path for negative weights
     Can also be used to detect negative weight cycles
     Pseudo code:
         Initialize ds = 0 and dv = ∞ ∀v = s
         For k = 1 . . . n-1:
         For each edge u → v of cost c:
            dv = min{dv , du + c }

     Runs in O(nm) time




                League of Programmers   Graphs
Outline




          League of Programmers   Graphs
Problems




  Links:
    1   http://www.spoj.pl/problems/IOPC1201/
    2   http://www.spoj.pl/problems/TRAFFICN/
    3   http://www.spoj.pl/problems/PFDEP/
    4   http://www.spoj.pl/problems/PRATA/
    5   http://www.spoj.pl/problems/ONEZERO/
    6   http://www.spoj.pl/problems/PPATH/
    7   http://www.spoj.pl/problems/PARADOX/
    8   http://www.spoj.pl/problems/HERDING/
    9   http://www.spoj.pl/problems/PT07Z/



                 League of Programmers   Graphs

Mais conteúdo relacionado

Mais procurados

Graph theory concepts complex networks presents-rouhollah nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabatinabati
 
Graph theory in network system
Graph theory in network systemGraph theory in network system
Graph theory in network systemManikanta satyala
 
Graph theory and its applications
Graph theory and its applicationsGraph theory and its applications
Graph theory and its applicationsManikanta satyala
 
Graph: Euler path and Euler circuit
Graph: Euler path and Euler circuitGraph: Euler path and Euler circuit
Graph: Euler path and Euler circuitLiwayway Memije-Cruz
 
Distruct week 15 graphs theory (updated)
Distruct week 15 graphs theory (updated)Distruct week 15 graphs theory (updated)
Distruct week 15 graphs theory (updated)Robert Almazan
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in indiaEdhole.com
 
Intro matlab and convolution islam
Intro matlab and convolution islamIntro matlab and convolution islam
Intro matlab and convolution islamIslam Alabbasy
 
Algorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph AlgorithmsAlgorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph AlgorithmsMohamed Loey
 
Elliptic Curve Cryptography: Arithmetic behind
Elliptic Curve Cryptography: Arithmetic behindElliptic Curve Cryptography: Arithmetic behind
Elliptic Curve Cryptography: Arithmetic behindAyan Sengupta
 
Projectors and Projection Onto Subspaces
Projectors and Projection Onto SubspacesProjectors and Projection Onto Subspaces
Projectors and Projection Onto SubspacesIsaac Yowetu
 

Mais procurados (20)

Lecture13
Lecture13Lecture13
Lecture13
 
Graph
GraphGraph
Graph
 
graph theory
graph theorygraph theory
graph theory
 
Graph theory concepts complex networks presents-rouhollah nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabati
 
Graph theory in network system
Graph theory in network systemGraph theory in network system
Graph theory in network system
 
Graph theory and its applications
Graph theory and its applicationsGraph theory and its applications
Graph theory and its applications
 
Graph: Euler path and Euler circuit
Graph: Euler path and Euler circuitGraph: Euler path and Euler circuit
Graph: Euler path and Euler circuit
 
Distruct week 15 graphs theory (updated)
Distruct week 15 graphs theory (updated)Distruct week 15 graphs theory (updated)
Distruct week 15 graphs theory (updated)
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
Graphs-LeX2-given
Graphs-LeX2-givenGraphs-LeX2-given
Graphs-LeX2-given
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
 
graph theory
graph theory graph theory
graph theory
 
Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
 
Graph theory
Graph theoryGraph theory
Graph theory
 
Exhaustive Combinatorial Enumeration
Exhaustive Combinatorial EnumerationExhaustive Combinatorial Enumeration
Exhaustive Combinatorial Enumeration
 
Intro matlab and convolution islam
Intro matlab and convolution islamIntro matlab and convolution islam
Intro matlab and convolution islam
 
Algorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph AlgorithmsAlgorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph Algorithms
 
Elliptic Curve Cryptography: Arithmetic behind
Elliptic Curve Cryptography: Arithmetic behindElliptic Curve Cryptography: Arithmetic behind
Elliptic Curve Cryptography: Arithmetic behind
 
Projectors and Projection Onto Subspaces
Projectors and Projection Onto SubspacesProjectors and Projection Onto Subspaces
Projectors and Projection Onto Subspaces
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
 

Destaque

Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKPankaj Prateek
 
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITKPankaj Prateek
 
JavaScript, the good parts + syntactic sugar = CoffeeScript
JavaScript, the good parts + syntactic sugar = CoffeeScript JavaScript, the good parts + syntactic sugar = CoffeeScript
JavaScript, the good parts + syntactic sugar = CoffeeScript geekQ
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ AdvancedVivek Das
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template LibraryAnirudh Raja
 
Front End Development - Beyond Javascript (Robin Cannon)
Front End Development - Beyond Javascript (Robin Cannon)Front End Development - Beyond Javascript (Robin Cannon)
Front End Development - Beyond Javascript (Robin Cannon)Future Insights
 
Top 10 things a fresh programmer should know - Dao Ngoc Khanh
Top 10 things a fresh programmer should know - Dao Ngoc KhanhTop 10 things a fresh programmer should know - Dao Ngoc Khanh
Top 10 things a fresh programmer should know - Dao Ngoc KhanhDevDay.org
 
02 greedy, d&c, binary search
02 greedy, d&c, binary search02 greedy, d&c, binary search
02 greedy, d&c, binary searchPankaj Prateek
 
Security in the Internet of Things
Security in the Internet of ThingsSecurity in the Internet of Things
Security in the Internet of ThingsForgeRock
 
Becoming a Better Programmer
Becoming a Better ProgrammerBecoming a Better Programmer
Becoming a Better ProgrammerPete Goodliffe
 

Destaque (13)

Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
 
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
 
03 dp
03 dp03 dp
03 dp
 
JavaScript, the good parts + syntactic sugar = CoffeeScript
JavaScript, the good parts + syntactic sugar = CoffeeScript JavaScript, the good parts + syntactic sugar = CoffeeScript
JavaScript, the good parts + syntactic sugar = CoffeeScript
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced
 
01 basics and stl
01 basics and stl01 basics and stl
01 basics and stl
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template Library
 
04 maths
04 maths04 maths
04 maths
 
Front End Development - Beyond Javascript (Robin Cannon)
Front End Development - Beyond Javascript (Robin Cannon)Front End Development - Beyond Javascript (Robin Cannon)
Front End Development - Beyond Javascript (Robin Cannon)
 
Top 10 things a fresh programmer should know - Dao Ngoc Khanh
Top 10 things a fresh programmer should know - Dao Ngoc KhanhTop 10 things a fresh programmer should know - Dao Ngoc Khanh
Top 10 things a fresh programmer should know - Dao Ngoc Khanh
 
02 greedy, d&c, binary search
02 greedy, d&c, binary search02 greedy, d&c, binary search
02 greedy, d&c, binary search
 
Security in the Internet of Things
Security in the Internet of ThingsSecurity in the Internet of Things
Security in the Internet of Things
 
Becoming a Better Programmer
Becoming a Better ProgrammerBecoming a Better Programmer
Becoming a Better Programmer
 

Semelhante a 05 graph

Graphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ programGraphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ programMuhammad Danish Badar
 
graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________ssuser1989da
 
Graph Introduction.ppt
Graph Introduction.pptGraph Introduction.ppt
Graph Introduction.pptFaruk Hossen
 
Semantic Data Management in Graph Databases
Semantic Data Management in Graph DatabasesSemantic Data Management in Graph Databases
Semantic Data Management in Graph DatabasesMaribel Acosta Deibe
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structuresSavit Chandra
 
Social network-analysis-in-python
Social network-analysis-in-pythonSocial network-analysis-in-python
Social network-analysis-in-pythonJoe OntheRocks
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptTalhaFarooqui12
 
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfClass01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfChristianKapsales1
 
Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashingVictor Palmar
 
Representing and visiting graphs
Representing and visiting graphsRepresenting and visiting graphs
Representing and visiting graphsFulvio Corno
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptxARVIND SARDAR
 
Slides Chapter10.1 10.2
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2showslidedump
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxking779879
 
Graph in Data Structure
Graph in Data StructureGraph in Data Structure
Graph in Data StructureProf Ansari
 
graph.pptx
graph.pptxgraph.pptx
graph.pptxhijigaf
 
Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - IAnirudh Raja
 

Semelhante a 05 graph (20)

Graphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ programGraphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ program
 
graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________
 
Graph Introduction.ppt
Graph Introduction.pptGraph Introduction.ppt
Graph Introduction.ppt
 
Semantic Data Management in Graph Databases
Semantic Data Management in Graph DatabasesSemantic Data Management in Graph Databases
Semantic Data Management in Graph Databases
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structures
 
Social network-analysis-in-python
Social network-analysis-in-pythonSocial network-analysis-in-python
Social network-analysis-in-python
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
 
09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf
 
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfClass01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
 
Graphs
GraphsGraphs
Graphs
 
Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashing
 
Representing and visiting graphs
Representing and visiting graphsRepresenting and visiting graphs
Representing and visiting graphs
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
 
Slides Chapter10.1 10.2
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptx
 
Graph in Data Structure
Graph in Data StructureGraph in Data Structure
Graph in Data Structure
 
Unit 2: All
Unit 2: AllUnit 2: All
Unit 2: All
 
graph.pptx
graph.pptxgraph.pptx
graph.pptx
 
Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - I
 

05 graph

  • 1. Graphs League of Programmers ACA, IIT Kanpur League of Programmers Graphs
  • 2. Outline League of Programmers Graphs
  • 3. Basics What are Graphs? League of Programmers Graphs
  • 4. Basics What are Graphs? An abstract way of representing connectivity using nodes (or vertices) and edges League of Programmers Graphs
  • 5. Basics What are Graphs? An abstract way of representing connectivity using nodes (or vertices) and edges Graph G=(V,E) , E ⊆ V ∗ V League of Programmers Graphs
  • 6. Basics What are Graphs? An abstract way of representing connectivity using nodes (or vertices) and edges Graph G=(V,E) , E ⊆ V ∗ V We will label the nodes from 1 to n (V) League of Programmers Graphs
  • 7. Basics What are Graphs? An abstract way of representing connectivity using nodes (or vertices) and edges Graph G=(V,E) , E ⊆ V ∗ V We will label the nodes from 1 to n (V) m edges connect some pairs of nodes (E) League of Programmers Graphs
  • 8. Basics What are Graphs? An abstract way of representing connectivity using nodes (or vertices) and edges Graph G=(V,E) , E ⊆ V ∗ V We will label the nodes from 1 to n (V) m edges connect some pairs of nodes (E) Edges can be either one-directional (directed) or bidirectional League of Programmers Graphs
  • 9. Basics What are Graphs? An abstract way of representing connectivity using nodes (or vertices) and edges Graph G=(V,E) , E ⊆ V ∗ V We will label the nodes from 1 to n (V) m edges connect some pairs of nodes (E) Edges can be either one-directional (directed) or bidirectional Nodes and edges can have some auxiliary information League of Programmers Graphs
  • 10. Basics Terminologies League of Programmers Graphs
  • 11. Basics Terminologies Vertex: node of a graph League of Programmers Graphs
  • 12. Basics Terminologies Vertex: node of a graph Adjacency(u) = {v |(u , v ) ∈ E } League of Programmers Graphs
  • 13. Basics Terminologies Vertex: node of a graph Adjacency(u) = {v |(u , v ) ∈ E } Degree(u) = |Adjacency(u)| League of Programmers Graphs
  • 14. Basics Terminologies Vertex: node of a graph Adjacency(u) = {v |(u , v ) ∈ E } Degree(u) = |Adjacency(u)| Subgraph: A subset of vertices and edges is a subgraph League of Programmers Graphs
  • 15. Basics Terminologies Vertex: node of a graph Adjacency(u) = {v |(u , v ) ∈ E } Degree(u) = |Adjacency(u)| Subgraph: A subset of vertices and edges is a subgraph Walk: A sequence v , v , . . . , v such that (v , v + ) ∈ E 1 2 k i i 1 League of Programmers Graphs
  • 16. Basics Terminologies Vertex: node of a graph Adjacency(u) = {v |(u , v ) ∈ E } Degree(u) = |Adjacency(u)| Subgraph: A subset of vertices and edges is a subgraph Walk: A sequence v , v , . . . , v such that (v , v + ) ∈ E 1 2 k i i 1 Trial: A trial is a walk in which no edge occurs twice League of Programmers Graphs
  • 17. Basics Terminologies Vertex: node of a graph Adjacency(u) = {v |(u , v ) ∈ E } Degree(u) = |Adjacency(u)| Subgraph: A subset of vertices and edges is a subgraph Walk: A sequence v , v , . . . , v such that (v , v + ) ∈ E 1 2 k i i 1 Trial: A trial is a walk in which no edge occurs twice Closed path: A walk where starting and ending vertex are the same League of Programmers Graphs
  • 18. Basics Storing Graphs League of Programmers Graphs
  • 19. Basics Storing Graphs We need to store both the set of nodes V and the set of edges E League of Programmers Graphs
  • 20. Basics Storing Graphs We need to store both the set of nodes V and the set of edges E Nodes can be stored in an array. Edges must be stored in some other way. League of Programmers Graphs
  • 21. Basics Storing Graphs We need to store both the set of nodes V and the set of edges E Nodes can be stored in an array. Edges must be stored in some other way. We want to support the following operations League of Programmers Graphs
  • 22. Basics Storing Graphs We need to store both the set of nodes V and the set of edges E Nodes can be stored in an array. Edges must be stored in some other way. We want to support the following operations Retrieving all edges incident to a particular node League of Programmers Graphs
  • 23. Basics Storing Graphs We need to store both the set of nodes V and the set of edges E Nodes can be stored in an array. Edges must be stored in some other way. We want to support the following operations Retrieving all edges incident to a particular node Testing if given two nodes are directly connected League of Programmers Graphs
  • 24. Basics Adjacency Matrix League of Programmers Graphs
  • 25. Basics Adjacency Matrix An easy way to store connectivity information League of Programmers Graphs
  • 26. Basics Adjacency Matrix An easy way to store connectivity information Checking if two nodes are directly connected: O(1) time League of Programmers Graphs
  • 27. Basics Adjacency Matrix An easy way to store connectivity information Checking if two nodes are directly connected: O(1) time Make an n x n matrix A League of Programmers Graphs
  • 28. Basics Adjacency Matrix An easy way to store connectivity information Checking if two nodes are directly connected: O(1) time Make an n x n matrix A a[i][j] = 1 if there is an edge from i to j League of Programmers Graphs
  • 29. Basics Adjacency Matrix An easy way to store connectivity information Checking if two nodes are directly connected: O(1) time Make an n x n matrix A a[i][j] = 1 if there is an edge from i to j a[i][j] = 0 otherwise League of Programmers Graphs
  • 30. Basics Adjacency Matrix An easy way to store connectivity information Checking if two nodes are directly connected: O(1) time Make an n x n matrix A a[i][j] = 1 if there is an edge from i to j a[i][j] = 0 otherwise Uses O(n ) memory. So, use when n is less than a few 2 thousands, AND when the graph is dense League of Programmers Graphs
  • 31. Basics Adjacency List League of Programmers Graphs
  • 32. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. League of Programmers Graphs
  • 33. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. Lists have variable lengths League of Programmers Graphs
  • 34. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. Lists have variable lengths We can use: vector< vector<int> > League of Programmers Graphs
  • 35. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. Lists have variable lengths We can use: vector< vector<int> > Space usage: O(n + m) League of Programmers Graphs
  • 36. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. Lists have variable lengths We can use: vector< vector<int> > Space usage: O(n + m) Checking if edge (Vi,Vj) is present in G: League of Programmers Graphs
  • 37. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. Lists have variable lengths We can use: vector< vector<int> > Space usage: O(n + m) Checking if edge (Vi,Vj) is present in G: League of Programmers Graphs
  • 38. Basics Adjacency List Each vertex maintains a list of vertices that are adjacent to it. Lists have variable lengths We can use: vector< vector<int> > Space usage: O(n + m) Checking if edge (Vi,Vj) is present in G: O(min(deg(Vi),deg(Vj))) League of Programmers Graphs
  • 39. Basics Special Graphs League of Programmers Graphs
  • 40. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. League of Programmers Graphs
  • 41. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. Tree: a connected acyclic graph The most important type of graph in CS Alternate denitions (all are equivalent!) League of Programmers Graphs
  • 42. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. Tree: a connected acyclic graph The most important type of graph in CS Alternate denitions (all are equivalent!) connected graph with n-1 edges League of Programmers Graphs
  • 43. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. Tree: a connected acyclic graph The most important type of graph in CS Alternate denitions (all are equivalent!) connected graph with n-1 edges An acyclic graph with n-1 edges League of Programmers Graphs
  • 44. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. Tree: a connected acyclic graph The most important type of graph in CS Alternate denitions (all are equivalent!) connected graph with n-1 edges An acyclic graph with n-1 edges There is exactly one path between every pair of nodes League of Programmers Graphs
  • 45. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. Tree: a connected acyclic graph The most important type of graph in CS Alternate denitions (all are equivalent!) connected graph with n-1 edges An acyclic graph with n-1 edges There is exactly one path between every pair of nodes An acyclic graph but adding any edge results in a cycle League of Programmers Graphs
  • 46. Basics Special Graphs Implicit graphs Two squares on an 8x8 chessboard. Determine the shortest sequence of knight moves from one square to the other. Tree: a connected acyclic graph The most important type of graph in CS Alternate denitions (all are equivalent!) connected graph with n-1 edges An acyclic graph with n-1 edges There is exactly one path between every pair of nodes An acyclic graph but adding any edge results in a cycle A connected graph but removing any edge disconnects it League of Programmers Graphs
  • 47. Basics Special Graphs League of Programmers Graphs
  • 48. Basics Special Graphs Directed Acyclic Graph (DAG) League of Programmers Graphs
  • 49. Basics Special Graphs Directed Acyclic Graph (DAG) Bipartite Graph Nodes can be separated into two groups S and T such that edges exist between S and T only (no edges within S or within T) League of Programmers Graphs
  • 50. Outline League of Programmers Graphs
  • 51. Traversal Graph Traversal League of Programmers Graphs
  • 52. Traversal Graph Traversal The most basic graph algorithm that visits nodes of a graph in certain order League of Programmers Graphs
  • 53. Traversal Graph Traversal The most basic graph algorithm that visits nodes of a graph in certain order Used as a subroutine in many other algorithms League of Programmers Graphs
  • 54. Traversal Graph Traversal The most basic graph algorithm that visits nodes of a graph in certain order Used as a subroutine in many other algorithms We will cover two algorithms League of Programmers Graphs
  • 55. Traversal Graph Traversal The most basic graph algorithm that visits nodes of a graph in certain order Used as a subroutine in many other algorithms We will cover two algorithms Depth-First Search (DFS): uses recursion League of Programmers Graphs
  • 56. Traversal Graph Traversal The most basic graph algorithm that visits nodes of a graph in certain order Used as a subroutine in many other algorithms We will cover two algorithms Depth-First Search (DFS): uses recursion Breadth-First Search (BFS): uses queue League of Programmers Graphs
  • 57. Traversal DFS League of Programmers Graphs
  • 58. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order League of Programmers Graphs
  • 59. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited League of Programmers Graphs
  • 60. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) League of Programmers Graphs
  • 61. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) Use non-recursive version if recursion depth is too big (over a few thousands) League of Programmers Graphs
  • 62. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) Use non-recursive version if recursion depth is too big (over a few thousands) Replace recursive calls with a stack League of Programmers Graphs
  • 63. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) Use non-recursive version if recursion depth is too big (over a few thousands) Replace recursive calls with a stack Complexity League of Programmers Graphs
  • 64. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) Use non-recursive version if recursion depth is too big (over a few thousands) Replace recursive calls with a stack Complexity League of Programmers Graphs
  • 65. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) Use non-recursive version if recursion depth is too big (over a few thousands) Replace recursive calls with a stack Complexity Time: O(|V|+|E|) League of Programmers Graphs
  • 66. Traversal DFS DFS(v): visits all the nodes reachable from v in depth-rst order Mark v as visited For each edge v → u : If u is not visited, call DFS(u) Use non-recursive version if recursion depth is too big (over a few thousands) Replace recursive calls with a stack Complexity Time: O(|V|+|E|) Space: O(|V|) [to maintain the vertices visited till now] League of Programmers Graphs
  • 67. Traversal DFS: Uses League of Programmers Graphs
  • 68. Traversal DFS: Uses Biconnected components League of Programmers Graphs
  • 69. Traversal DFS: Uses Biconnected components A node in a connected graph is called an articulation point if the deletion of that node disconnects the graph. League of Programmers Graphs
  • 70. Traversal DFS: Uses Biconnected components A node in a connected graph is called an articulation point if the deletion of that node disconnects the graph. A connected graph is called biconnected if it has no articulation points. That is, the deletion of any single node leaves the graph connected. League of Programmers Graphs
  • 71. Traversal BFS BFS(v): visits all the nodes reachable from v in breadth-rst order League of Programmers Graphs
  • 72. Traversal BFS BFS(v): visits all the nodes reachable from v in breadth-rst order Initialize a queue Q League of Programmers Graphs
  • 73. Traversal BFS BFS(v): visits all the nodes reachable from v in breadth-rst order Initialize a queue Q Mark v as visited and push it to Q League of Programmers Graphs
  • 74. Traversal BFS BFS(v): visits all the nodes reachable from v in breadth-rst order Initialize a queue Q Mark v as visited and push it to Q While Q is not empty: Take the front element of Q and call it w For each edge w → u : If u is not visited, mark it as visited and push it to Q League of Programmers Graphs
  • 75. Traversal BFS BFS(v): visits all the nodes reachable from v in breadth-rst order Initialize a queue Q Mark v as visited and push it to Q While Q is not empty: Take the front element of Q and call it w For each edge w → u : If u is not visited, mark it as visited and push it to Q Same Time and Space Complexity as DFS League of Programmers Graphs
  • 76. Traversal BFS: Uses League of Programmers Graphs
  • 77. Traversal BFS: Uses Finding a Path with Minimum Number of edges from starting vertex to any other vertex. League of Programmers Graphs
  • 78. Traversal BFS: Uses Finding a Path with Minimum Number of edges from starting vertex to any other vertex. Solve Shortest Path problem in unweighted graphs League of Programmers Graphs
  • 79. Traversal BFS: Uses Finding a Path with Minimum Number of edges from starting vertex to any other vertex. Solve Shortest Path problem in unweighted graphs Spoj Problem http://www.spoj.pl/problems/PPATH/ League of Programmers Graphs
  • 80. Topological Sort League of Programmers Graphs
  • 81. Topological Sort Input: a DAG G = V, E League of Programmers Graphs
  • 82. Topological Sort Input: a DAG G = V, E Output: an ordering of nodes such that for each edge u → v , u comes before v. There can be many answers League of Programmers Graphs
  • 83. Topological Sort Input: a DAG G = V, E Output: an ordering of nodes such that for each edge u → v , u comes before v. There can be many answers Pseudocode League of Programmers Graphs
  • 84. Topological Sort Input: a DAG G = V, E Output: an ordering of nodes such that for each edge u → v , u comes before v. There can be many answers Pseudocode Precompute the number of incoming edges deg(v) for each node v League of Programmers Graphs
  • 85. Topological Sort Input: a DAG G = V, E Output: an ordering of nodes such that for each edge u → v , u comes before v. There can be many answers Pseudocode Precompute the number of incoming edges deg(v) for each node v Put all nodes with zero degree into a queue Q League of Programmers Graphs
  • 86. Topological Sort Input: a DAG G = V, E Output: an ordering of nodes such that for each edge u → v , u comes before v. There can be many answers Pseudocode Precompute the number of incoming edges deg(v) for each node v Put all nodes with zero degree into a queue Q Repeat until Q becomes empty: Take v from Q For each edge v → u Decrement deg(u) (essentially removing the edge v → u ) If deg u becomes zero, push u to Q League of Programmers Graphs
  • 87. Topological Sort Input: a DAG G = V, E Output: an ordering of nodes such that for each edge u → v , u comes before v. There can be many answers Pseudocode Precompute the number of incoming edges deg(v) for each node v Put all nodes with zero degree into a queue Q Repeat until Q becomes empty: Take v from Q For each edge v → u Decrement deg(u) (essentially removing the edge v → u ) If deg u becomes zero, push u to Q Time complexity: O (n + m) League of Programmers Graphs
  • 88. Outline League of Programmers Graphs
  • 89. Minimum Spanning Tree League of Programmers Graphs
  • 90. Minimum Spanning Tree Input: An undirected weighted graph G = V, E League of Programmers Graphs
  • 91. Minimum Spanning Tree Input: An undirected weighted graph G = V, E Output: A subset of E with the minimum total weight that connects all the nodes into a tree League of Programmers Graphs
  • 92. Minimum Spanning Tree Input: An undirected weighted graph G = V, E Output: A subset of E with the minimum total weight that connects all the nodes into a tree There are two algorithms: League of Programmers Graphs
  • 93. Minimum Spanning Tree Input: An undirected weighted graph G = V, E Output: A subset of E with the minimum total weight that connects all the nodes into a tree There are two algorithms: Kruskal's algorithm League of Programmers Graphs
  • 94. Minimum Spanning Tree Input: An undirected weighted graph G = V, E Output: A subset of E with the minimum total weight that connects all the nodes into a tree There are two algorithms: Kruskal's algorithm Prim's algorithm League of Programmers Graphs
  • 95. Kruskal's Algorithm League of Programmers Graphs
  • 96. Kruskal's Algorithm Main idea: the edge e with the smallest weight has to be in the MST League of Programmers Graphs
  • 97. Kruskal's Algorithm Main idea: the edge e with the smallest weight has to be in the MST Keep dierent supernodes, which are local MST's and then join them by adding edges to form the MST for the whole graph League of Programmers Graphs
  • 98. Kruskal's Algorithm Main idea: the edge e with the smallest weight has to be in the MST Keep dierent supernodes, which are local MST's and then join them by adding edges to form the MST for the whole graph Pseudocode: Sort the edges in increasing order of weight Repeat until there is one supernode left: Take the minimum weight edge e* If e* connects two different supernodes: Connect them and merge the supernodes Otherwise, ignore e* League of Programmers Graphs
  • 99. Prim's Algorithm Prim's Algo Reading Homework League of Programmers Graphs
  • 100. Outline League of Programmers Graphs
  • 101. Floyd-Warshall Algorithm League of Programmers Graphs
  • 102. Floyd-Warshall Algorithm All pair shortest distance League of Programmers Graphs
  • 103. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 League of Programmers Graphs
  • 104. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm League of Programmers Graphs
  • 105. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes League of Programmers Graphs
  • 106. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes f(i, j, n) is the shortest distance from i to j League of Programmers Graphs
  • 107. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes f(i, j, n) is the shortest distance from i to j f(i, j, 0) = cost(i, j) League of Programmers Graphs
  • 108. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes f(i, j, n) is the shortest distance from i to j f(i, j, 0) = cost(i, j) The optimal path for f i, j, k may or may not have k as an intermediate node League of Programmers Graphs
  • 109. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes f(i, j, n) is the shortest distance from i to j f(i, j, 0) = cost(i, j) The optimal path for f i, j, k may or may not have k as an intermediate node If it does, f (i, j, k) = f (i,k k-1) + f(k, j, k-1) League of Programmers Graphs
  • 110. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes f(i, j, n) is the shortest distance from i to j f(i, j, 0) = cost(i, j) The optimal path for f i, j, k may or may not have k as an intermediate node If it does, f (i, j, k) = f (i,k k-1) + f(k, j, k-1) Otherwise, f (i, j, k) = f (i, j, k-1) League of Programmers Graphs
  • 111. Floyd-Warshall Algorithm All pair shortest distance Runs in O(n ) time 3 Algorithm Dene f(i, j, k) as the shortest distance from i to j, using 1 ... k as intermediate nodes f(i, j, n) is the shortest distance from i to j f(i, j, 0) = cost(i, j) The optimal path for f i, j, k may or may not have k as an intermediate node If it does, f (i, j, k) = f (i,k k-1) + f(k, j, k-1) Otherwise, f (i, j, k) = f (i, j, k-1) Therefore, f (i, j, k) is the minimum of the two quantities above League of Programmers Graphs
  • 112. Floyd-Warshall Algorithm League of Programmers Graphs
  • 113. Floyd-Warshall Algorithm Pseudocode: Initialize D to the given cost matrix For k = 1 ...n: For all i and j: d = min{d , d + d } ij ij ik kj League of Programmers Graphs
  • 114. Floyd-Warshall Algorithm Pseudocode: Initialize D to the given cost matrix For k = 1 ...n: For all i and j: d = min{d , d + d } ij ij ik kj Can also be used to detect negative weight cycles in graph? League of Programmers Graphs
  • 115. Floyd-Warshall Algorithm Pseudocode: Initialize D to the given cost matrix For k = 1 ...n: For all i and j: d = min{d , d + d } ij ij ik kj Can also be used to detect negative weight cycles in graph? League of Programmers Graphs
  • 116. Floyd-Warshall Algorithm Pseudocode: Initialize D to the given cost matrix For k = 1 ...n: For all i and j: d = min{d , d + d } ij ij ik kj Can also be used to detect negative weight cycles in graph? How? League of Programmers Graphs
  • 117. Floyd-Warshall Algorithm Pseudocode: Initialize D to the given cost matrix For k = 1 ...n: For all i and j: d = min{d , d + d } ij ij ik kj Can also be used to detect negative weight cycles in graph? How? If d + d 0 for some i and j, then the graph has a negative ij ji weight cycle League of Programmers Graphs
  • 118. Dijkstra's Algorithm League of Programmers Graphs
  • 119. Dijkstra's Algorithm Used to solve Single source Shortest Path problem in Weighted Graphs League of Programmers Graphs
  • 120. Dijkstra's Algorithm Used to solve Single source Shortest Path problem in Weighted Graphs Only for Graphs with positive edge weights. League of Programmers Graphs
  • 121. Dijkstra's Algorithm Used to solve Single source Shortest Path problem in Weighted Graphs Only for Graphs with positive edge weights. The algorithm nds the path with lowest cost (i.e. the shortest path) between that source vertex and every other vertex League of Programmers Graphs
  • 122. Dijkstra's Algorithm Used to solve Single source Shortest Path problem in Weighted Graphs Only for Graphs with positive edge weights. The algorithm nds the path with lowest cost (i.e. the shortest path) between that source vertex and every other vertex Greedy strategy League of Programmers Graphs
  • 123. Dijkstra's Algorithm Used to solve Single source Shortest Path problem in Weighted Graphs Only for Graphs with positive edge weights. The algorithm nds the path with lowest cost (i.e. the shortest path) between that source vertex and every other vertex Greedy strategy Idea: Find the closest node to s, and then the second closest one, then the third, etc League of Programmers Graphs
  • 124. Dijkstra's Algorithm League of Programmers Graphs
  • 125. Dijkstra's Algorithm Pseudo code: League of Programmers Graphs
  • 126. Dijkstra's Algorithm Pseudo code: Maintain a set of nodes S, the shortest distances to which are decided League of Programmers Graphs
  • 127. Dijkstra's Algorithm Pseudo code: Maintain a set of nodes S, the shortest distances to which are decided Also maintain a vector d, the shortest distance estimate from s League of Programmers Graphs
  • 128. Dijkstra's Algorithm Pseudo code: Maintain a set of nodes S, the shortest distances to which are decided Also maintain a vector d, the shortest distance estimate from s Initially, S = s, and dv = cost(s, v) League of Programmers Graphs
  • 129. Dijkstra's Algorithm Pseudo code: Maintain a set of nodes S, the shortest distances to which are decided Also maintain a vector d, the shortest distance estimate from s Initially, S = s, and dv = cost(s, v) Repeat until S = V: Find v ∈ S with the smallest dv , and add it to S / For each edge v → u of cost c: du = min{du , dv + c } League of Programmers Graphs
  • 130. Dijkstra's Algorithm League of Programmers Graphs
  • 131. Dijkstra's Algorithm Time complexity depends on the implementation: Can be O(n + m), O(m log n), O(n log n) 2 League of Programmers Graphs
  • 132. Dijkstra's Algorithm Time complexity depends on the implementation: Can be O(n + m), O(m log n), O(n log n) 2 Use priority_queuenode for implementing Dijkstra's League of Programmers Graphs
  • 133. Dijkstra's Algorithm Time complexity depends on the implementation: Can be O(n + m), O(m log n), O(n log n) 2 Use priority_queuenode for implementing Dijkstra's SPOJ Problem http://www.spoj.pl/problems/CHICAGO League of Programmers Graphs
  • 134. Bellman-Ford Algorithm League of Programmers Graphs
  • 135. Bellman-Ford Algorithm Single source shortest path for negative weights League of Programmers Graphs
  • 136. Bellman-Ford Algorithm Single source shortest path for negative weights Can also be used to detect negative weight cycles League of Programmers Graphs
  • 137. Bellman-Ford Algorithm Single source shortest path for negative weights Can also be used to detect negative weight cycles Pseudo code: League of Programmers Graphs
  • 138. Bellman-Ford Algorithm Single source shortest path for negative weights Can also be used to detect negative weight cycles Pseudo code: Initialize ds = 0 and dv = ∞ ∀v = s League of Programmers Graphs
  • 139. Bellman-Ford Algorithm Single source shortest path for negative weights Can also be used to detect negative weight cycles Pseudo code: Initialize ds = 0 and dv = ∞ ∀v = s For k = 1 . . . n-1: League of Programmers Graphs
  • 140. Bellman-Ford Algorithm Single source shortest path for negative weights Can also be used to detect negative weight cycles Pseudo code: Initialize ds = 0 and dv = ∞ ∀v = s For k = 1 . . . n-1: For each edge u → v of cost c: dv = min{dv , du + c } League of Programmers Graphs
  • 141. Bellman-Ford Algorithm Single source shortest path for negative weights Can also be used to detect negative weight cycles Pseudo code: Initialize ds = 0 and dv = ∞ ∀v = s For k = 1 . . . n-1: For each edge u → v of cost c: dv = min{dv , du + c } Runs in O(nm) time League of Programmers Graphs
  • 142. Outline League of Programmers Graphs
  • 143. Problems Links: 1 http://www.spoj.pl/problems/IOPC1201/ 2 http://www.spoj.pl/problems/TRAFFICN/ 3 http://www.spoj.pl/problems/PFDEP/ 4 http://www.spoj.pl/problems/PRATA/ 5 http://www.spoj.pl/problems/ONEZERO/ 6 http://www.spoj.pl/problems/PPATH/ 7 http://www.spoj.pl/problems/PARADOX/ 8 http://www.spoj.pl/problems/HERDING/ 9 http://www.spoj.pl/problems/PT07Z/ League of Programmers Graphs