SlideShare a Scribd company logo
1 of 57
Graph

Md. Shakil Ahmed
Software Engineer
Astha it research & consultancy ltd.
Dhaka, Bangladesh
Introduction
Topic Focus:
• Graph Representation
• DFS
• BFS
• Union Find
• Kruskal's algorithm
• Floyd-Warshall's Algorithm
• Dijkstra's Algorithm
• Bipartite graph
Graph




a) An undirected graph and (b) a directed graph.
Definitions and Representation



  An undirected graph and its adjacency matrix representation.




An undirected graph and its adjacency list representation.
Depth-First Search
• Depth-first search is a systematic
  way to find all the vertices
  reachable from a source vertex, s.
• Historically, depth-first was first
  stated formally hundreds of years
  ago as a method for traversing
  mazes.
• The basic idea of depth-first search
  is this: It methodically explore
  every edge. We start over from
  different vertices as necessary. As
  soon as we discover a vertex, DFS
  starts exploring from it
Depth-First Search
Depth-First Search
procedure DFS(G,v):
label v as explored
for all edges e in G.incidentEdges(v) do
    if edge e is unexplored then
          w ← G.opposite(v,e)
          if vertex w is unexplored then
                    label e as a discovery edge
                    recursively call DFS(G,w)
DFS Source Code
void DFS(long node)
{
    long i;
    printf(“%ld “,node);
    visit[node]=1;
    for(i=1;i<=n;i++)
           if(visit[i]==0&&A[node][i]==1)
                       DFS(i);
}
visit[]={0};
A[][] = connection matrix.
n = number of nodes, from 1 to n.
source = 1;
DFS(source);
Sample
• UVA Online Judge: 260, 352, 469, 572, 776,
  784, 871, 1197, 10336, 10946, 11110, 11244,
  11470, 11518.
Breadth-first search
• In graph theory, breadth-first
search (BFS) is a
graph search algorithm that
begins at the root node and
explores all the neighboring
nodes.
• Then for each of those
nearest nodes, it explores
their unexplored neighbor
nodes, and so on, until it finds
the goal.
                                   11
More BFS
More BFS
BFS Pseudo-Code
Step 1: Initialize all nodes to ready state (status = 1)
Step 2: Put the starting node in queue and change its status to
   the waiting state (status = 2)
Step 3: Repeat step 4 and 5 until queue is empty
Step 4: Remove the front node n of queue. Process n and
   change the status of n to the processed state (status = 3)
Step 5: Add to the rear of the queue all the neighbors of n that
   are in ready state (status = 1), and change their status to the
   waiting state (status = 2).
[End of the step 3 loop]
Step 6: Exit

                                                              14
BFS Source Code
                                        }
visit[]={0};                            N++;
A[][] = connection matrix.              }
n = number of nodes, from 1 to n.       for(i=0;i<M;i++)
    source = 1;                         printf(“%ld “,temp[i]);
    temp[0]=source;
    visit[ source ]=1;
    N = 0; M = 1;
while(N!=M)
    {
    for(i=1;i<=n;i++)
    if(A[temp[N]][i]==1&&visit[i]==0)
    {
           visit[i]=1;
           temp[M]=i;
           M++;
Sample
• UVA Online Judge: 336, 383, 429, 439, 532,
  567, 627, 762, 924, 10009, 10067, 10422,
  10610, 10653, 10959, 10977, 11049, 11101,
  11352, 11624, 11974, 12160.
DFS vs. BFS
    DFS Process                   F            B            A     start
                      E

                                  G            D            C
                          destination


                                        C   DFS on C    D       Call DFS on D
                  B   DFS on B          B               B       Return to call on B
A    DFS on A     A                     A               A


G     Call DFS on G             found destination - done!
                                Path is implicitly stored in DFS recursion
D                               Path is: A, B, D, G
B
A
DFS vs. BFS
                                          F           B           A       start
                             E
   BFS Process
                                       G              D           C
                             destination

rear         front               rear         front   rear        front            rear       front

              A                               B                D C                            D
  Initial call to BFS on A          Dequeue A             Dequeue B                  Dequeue C
  Add A to queue                        Add B               Add C, D              Nothing to add
 rear          front


               G                        found destination - done!
                                        Path must be stored separately
       Dequeue D
           Add G
Union Find
• Union Find is an algorithm which uses a
   disjoint-set data structure to solve the following problem:
   Say we have some number of items. We are allowed to
   merge any two items to consider them equal (where
   equality here obeys all of the properties of an
   Equivalence Relation). At any point, we are allowed to ask
   whether two items are considered equal or not.
• Basically a Union Find data structure implements two
   functions:
1. union( A, B ) - merge A's set with B's set
2. find( A ) - finds what set A belongs to
Union Find
Union Find Pseudocode
func find( var element )
   while ( element is not the root )
         element = element's parent
   return element
end func

func union( var setA, var setB )
   var rootA = find( setA )
   rootB = find( setB )
   if ( rootA is equal to rootB )
          return
   else
          set rootB as rootA's parent
end func
Union Find
Union Find Source Code
long Parent(long h1)
{
    if(P[h1]==-1)                             To find, any two members
    return h1;                                are same or different group
    P[h1] = Parent(P[h1]);                    for(i=1;i<=k;i++)
    return P[h1];                             {
                                              scanf(“%ld %ld”,&x,&y);
}
                                              x1 = Parent(x);
for(i=1;i<=n;i++) // n number of thing        y1 = Parent(y);
    P[i]=-1;                                  if(x1!=y1)
for(i=1;i<=m;i++) // m number of connection   printf(“Differentn”);
                                              else
{                                             printf(“Samen”);
    scanf(“%ld %ld”,&x,&y);                   }
    x1 = Parent(x);
    y1 = Parent(y);
    if(x1!=y1)
    P[x1]=y1;
}
Sample
• UVA Online Judge: 459, 793, 10158, 10369,
  10583, 10608, 10685, 11503.
Minimum Spanning Tree
• A spanning tree of an undirected graph G is a
  subgraph of G that is a tree containing all the
  vertices of G.
• In a weighted graph, the weight of a subgraph
  is the sum of the weights of the edges in the
  subgraph.
• A minimum spanning tree (MST) for a
  weighted undirected graph is a spanning tree
  with minimum weight.
Minimum Spanning Tree



An undirected graph and its minimum spanning tree.
Kruskal's algorithm
• Kruskal's algorithm is an algorithm in graph theory that
  finds a minimum spanning tree for a connected
  weighted graph. This means it finds a subset of the edges
   that forms a tree that includes every vertex, where the
  total weight of all the edges in the tree is minimized. If the
  graph is not connected, then it finds a minimum spanning
  forest (a minimum spanning tree for each connected
  component).
• Kruskal's algorithm is an example of a greedy algorithm.
Kruskal's algorithm Pseudocode
1    (Sort the edges in an increasing order)
2    A:={}
3    while E is not empty do {
3      take an edge (u, v) that is shortest in E
       and delete it from E
4      if u and v are in different components then
             add (u, v) to A
       }


                                                     28
The execution of Kruskal's algorithm (Moderate part)

 •The edges are considered by the algorithm in sorted order by weight.
 •The edge under consideration at each step is shown with a red weight
 number.




                                    8                   7
                            b                   c           d        9
                   4
                                            2
               a       11                                       14       e
                                    i               4
                                7           6
                                                                     10
                   8
                            h                   g           f
                                        1               2

                                                                             29
8                   7
             b                       c               d        9
    4
                                 2
a       11                                               14        e
                         i               4
                 7               6
                                                              10
    8
             h                       g               f
                             1                   2




                     8                       7
             b                       c               d        9
    4
                                 2
a       11                                               14       e
                     i                   4
                 7               6
                                                              10
    8
             h                       g               f
                         1                   2

                                                                       30
8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2



                     8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2

                                                              31
8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2


                     8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2

                                                              32
8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2



                     8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2

                                                              33
8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2


                     8                   7
             b                   c           d        9
    4
                             2
a       11                                       14       e
                     i               4
                 7           6
                                                      10
    8
             h                   g           f
                         1               2

                                                              34
Kruskal's algorithm Source Code
                                          for(i=1;i<=n;i++) // n number of node
struct T                                  P[i]=-1;
    {                                     for(i=0;i<m;i++) // m number of edge
    long x;                               scanf(“%ld %ld
    long y;                               %ld”,&a[i].x,&a[i].y,&a[i].weight);
    long weight;                          qsort(a,m,sizeof(T),cmp);
    };                                    cost = 0;
                                          for(i=0;i<m;i++)
T a[1000009];
                                          {
int cmp( const void *a, const void *b )   x = Parent(a[i].x);
    {                                     y = Parent(a[i].y);
    T *p = (T *)a;                        if(x!=y)
    T *q = (T *)b;                        {
                                          cost+=a[i].weight;
return ( p->weight – q->weight );
                                          P[x]=y;
    }                                     }
                                          }
                                          printf(“%ldn”,cost);
Sample
• UVA Online Judge: 544, 908, 10034, 10369,
  10048, 10147, 10397, 10600, 10842, 11631,
  11710, 11747.
Floyd-Warshall's Algorithm
• The Floyd-Warshall Algorithm is an efficient
  algorithm to find all-pairs shortest paths on a
  graph.
• That is, it is guaranteed to find the shortest
  path between every pair of vertices in a
  graph.
• The graph may have negative weight edges,
  but no negative weight cycles (for then the
  shortest path is undefined).
Floyd-Warshall
 for (int k = 1; k =< V; k++)
  for (int i = 1; i =< V; i++)
   for (int j = 1; j =< V; j++)
    if ( ( M[i][k]+ M[k][j] ) < M[i][j] )
      M[i][j] =       M[i][k]+ M[k][j]




Invariant: After the kth iteration, the matrix includes the shortest paths for all
pairs of vertices (i,j) containing only vertices 1..k as intermediate vertices
a       2       b
                                                         -2
Initial state of the                     1
                                -4               3            c
matrix:
                                     d                   1
                                                 e
    a    b    c        d    e            4
a   0    2    -        -4   -
b   -    0    -2       1    3
c   -    -    0        -    1
d   -    -    -        0    4
e   -    -    -        -    0

    M[i][j] = min(M[i][j], M[i][k]+ M[k][j])
a         2       b
                                                          -2
Floyd-Warshall - for
                                         1
All-pairs shortest             -4                 3            c
path
                                    d                     1
                                                  e
                                          4
        a   b   c      d   e
    a   0   2   0      -4 0
    b   -   0   -2 1       -1           Final Matrix
                                        Contents
    c   -   -   0      -   1
    d   -   -   -      0   4
    e   -   -   -      -   0
Sample
• UVA Online Judge: 104, 125, 186, 436, 523,
  821, 10075, 10171, 10793, 10803, 11015.
Single-Source Shortest Paths
• For a weighted graph G = (V,E,w), the single-
  source shortest paths problem is to find the
  shortest paths from a vertex v ∈ V to all
  other vertices in V.
• Dijkstra's algorithm maintains a set of nodes
  for which the shortest paths are known.
• It grows this set based on the node closest to
  source using one of the nodes in the current
  shortest path set.
Single-Source Shortest Paths: Dijkstra's
              Algorithm
function Dijkstra(Graph, source)
   for each vertex v in Graph: // Initializations
         dist[v] := infinity ;
         previous[v] := undefined ;
   end for ;
   dist[source] := 0 ;
   Q := the set of all nodes in Graph ;
   while Q is not empty:
         u := vertex in Q with smallest distance in dist[] ;
         if dist[u] = infinity:
                    break ;
         end if ;
remove u from Q ;
         for each neighbor v of u:
                   alt := dist[u] + dist_between(u, v) ;
                   if alt < dist[v]:
                              dist[v] := alt ;
                               previous[v] := u ;
                    end if ;
         end for ;
   end while ;
return dist[] ;
end Dijkstra.
Example
                                   u                                v
                                                   1
                                   ∞                                ∞

                          10
                                                    9
                               2       3
               s      0                                         4       6


                          5                             7

                                   ∞                                ∞
                                                   2
                                   x                                y




Comp 122, Fall 2003                    Single-source SPs - 45
Example
                                   u                                 v
                                                    1
                                   10                                ∞

                          10
                                                     9
                               2        3
               s      0                                          4       6


                          5                              7

                                   5                                 ∞
                                                    2
                                   x                                 y




Comp 122, Fall 2003                     Single-source SPs - 46
Example
                                   u                                v
                                                   1
                                   8                                14

                          10
                                                    9
                               2       3
               s      0                                         4        6


                          5                             7

                                   5                                7
                                                   2
                                   x                                y




Comp 122, Fall 2003                    Single-source SPs - 47
Example
                                   u                                v
                                                   1
                                   8                                13

                          10
                                                    9
                               2       3
               s      0                                         4        6


                          5                             7

                                   5                                7
                                                   2
                                   x                                y




Comp 122, Fall 2003                    Single-source SPs - 48
Example
                                   u                                v
                                                   1
                                   8                                9

                          10
                                                    9
                               2       3
               s      0                                         4       6


                          5                             7

                                   5                                7
                                                   2
                                   x                                y




Comp 122, Fall 2003                    Single-source SPs - 49
Example
                                   u                                v
                                                   1
                                   8                                9

                          10
                                                    9
                               2       3
               s      0                                         4       6


                          5                             7

                                   5                                7
                                                   2
                                   x                                y




Comp 122, Fall 2003                    Single-source SPs - 50
Dijkstra Source Code
#include <cstdio>                                 vector< pii > G[MAX];
                                                  int D[MAX];
#include <queue>
                                                  bool F[MAX];
#include <vector>                                 vector< pii > G[MAX];
using namespace std;                              int D[MAX];
#define MAX 100001                                bool F[MAX];
#define INF (1<<20)
#define DEBUG if(0)
#define pii pair< int, int >
#define pb(x) push_back(x)
struct comp {
   bool operator() (const pii &a, const pii &b)
     {
       return a.second > b.second;
   }
};
priority_queue< pii, vector< pii >, comp > Q;
if(F[u]) continue;
int main() {                                        sz = G[u].size();
int i, u, v, w, sz, nodes, edges, starting;
                                                    for(i=0; i<sz; i++) {
scanf("%d %d", &nodes, &edges);                       v = G[u][i].first;
  for(i=0; i<edges; i++) {                            w = G[u][i].second;
      scanf("%d %d %d", &u, &v, &w);                  if(!F[v] && D[u]+w < D[v]) {
      G[u].pb(pii(v, w));                                D[v] = D[u] + w;
                                                         Q.push(pii(v, D[v]));
      G[v].pb(pii(u, w)); // for
                                                       }
    undirected
                                                    }
  }
   scanf("%d", &starting);                          F[u] = 1; // done with u
   for(i=1; i<=nodes; i++) D[i] = INF;          }
   D[starting] = 0;
                                              for(i=1; i<=nodes; i++)
   Q.push(pii(starting, 0));
                                              printf("Node %d, min weight = %dn", i,
  // dijkstra                                 D[i]);
   while(!Q.empty()) {                         return 0;
      u = Q.top().first;                      }
      Q.pop();
Sample
• UVA Online Judge: 10986, 423, 10801, 10917,
  10986, 11338, 11813.
Bipartite graph
• In the mathematical field of graph
  theory, a bipartite graph (or bigraph) is
  a graph whose vertices can be divided
  into two disjoint sets U and V such that
  every edge connects a vertex in U to one
  in V; that is, U and V are independent
  sets. Equivalently, a bipartite graph is a
  graph that does not contain any odd-
  length cycles.
• We can use bfs or dfs for checking
  Bipartite graph.
Bipartite graph Using DFS
void BiColor(long node)                     color[]={-1};
{                                           A[][] = connection matrix.
long i;                                     n = number of nodes, from 1 to n.
                                            yes = 1;
for(i=1;i<=n;i++)                           for(i=1;i<=n;i++)
  if(A[node][i]==1)                         if(color[i]==-1)
     {                                      {
     if(color[i]==-1)                       color[i]=0;
     {                                      BiColor(i);
         color[i] = (color[node] + 1 )%2;   }
          BiColor(i);                       if(yes==1)
     }                                      printf(“possiblen”);
     else if(color[i]==color[node])         else
          yes = 0;                          printf(“not possiblen”);
     if(yes==0)
       break;
     }
}
Sample
• UVA Online Judge: 10004, 11080, 11396.
Thanks!

More Related Content

What's hot

Breadth first search and depth first search
Breadth first search and  depth first searchBreadth first search and  depth first search
Breadth first search and depth first searchHossain Md Shakhawat
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]DEEPIKA T
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First SearchDepth First Search and Breadth First Search
Depth First Search and Breadth First SearchBenjamin Sach
 
Breadth first search (Bfs)
Breadth first search (Bfs)Breadth first search (Bfs)
Breadth first search (Bfs)Ishucs
 
Data structures and algorithms lab7
Data structures and algorithms lab7Data structures and algorithms lab7
Data structures and algorithms lab7Bianca Teşilă
 
Graph Algorithms: Breadth-First Search (BFS)
Graph Algorithms: Breadth-First Search (BFS)Graph Algorithms: Breadth-First Search (BFS)
Graph Algorithms: Breadth-First Search (BFS)Md. Shafiuzzaman Hira
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02Krish_ver2
 
Breadth First Search (BFS)
Breadth First Search (BFS)Breadth First Search (BFS)
Breadth First Search (BFS)Dhrumil Panchal
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First SearchDepth First Search and Breadth First Search
Depth First Search and Breadth First SearchNisha Soms
 
lecture 18
lecture 18lecture 18
lecture 18sajinsc
 
Skiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first searchSkiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first searchzukun
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Shuvongkor Barman
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFSRajandeep Gill
 

What's hot (20)

Breadth first search and depth first search
Breadth first search and  depth first searchBreadth first search and  depth first search
Breadth first search and depth first search
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
Bfs
BfsBfs
Bfs
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First SearchDepth First Search and Breadth First Search
Depth First Search and Breadth First Search
 
Breadth first search (Bfs)
Breadth first search (Bfs)Breadth first search (Bfs)
Breadth first search (Bfs)
 
Breadth first search
Breadth first searchBreadth first search
Breadth first search
 
Data structures and algorithms lab7
Data structures and algorithms lab7Data structures and algorithms lab7
Data structures and algorithms lab7
 
BFS
BFSBFS
BFS
 
Graph Algorithms: Breadth-First Search (BFS)
Graph Algorithms: Breadth-First Search (BFS)Graph Algorithms: Breadth-First Search (BFS)
Graph Algorithms: Breadth-First Search (BFS)
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02
 
Breadth First Search (BFS)
Breadth First Search (BFS)Breadth First Search (BFS)
Breadth First Search (BFS)
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
 
Depth-First Search
Depth-First SearchDepth-First Search
Depth-First Search
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First SearchDepth First Search and Breadth First Search
Depth First Search and Breadth First Search
 
lecture 18
lecture 18lecture 18
lecture 18
 
Skiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first searchSkiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first search
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 

Similar to Graph

Analysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsAnalysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsSigSegVSquad
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivityzukun
 
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docxgraphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docxwhittemorelucilla
 
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm EData Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm Ejeniihykdevara
 
Lecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfLecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfiftakhar8
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treeoneous
 
Data Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docxData Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docxrandyburney60861
 
FADML 06 PPC Graphs and Traversals.pdf
FADML 06 PPC Graphs and Traversals.pdfFADML 06 PPC Graphs and Traversals.pdf
FADML 06 PPC Graphs and Traversals.pdfYelah1
 
Chapter3 Search
Chapter3 SearchChapter3 Search
Chapter3 SearchKhiem Ho
 
Dfs presentation
Dfs presentationDfs presentation
Dfs presentationAlizay Khan
 
Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7Traian Rebedea
 
Link Prediction in the Real World
Link Prediction in the Real WorldLink Prediction in the Real World
Link Prediction in the Real WorldBalaji Ganesan
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structuresSavit Chandra
 

Similar to Graph (20)

Algorithm
AlgorithmAlgorithm
Algorithm
 
Analysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsAnalysis of Pathfinding Algorithms
Analysis of Pathfinding Algorithms
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivity
 
Lecture13
Lecture13Lecture13
Lecture13
 
ALG5.1.ppt
ALG5.1.pptALG5.1.ppt
ALG5.1.ppt
 
DFS and BFS
DFS and BFSDFS and BFS
DFS and BFS
 
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docxgraphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
 
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm EData Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
 
Topological sort
Topological sortTopological sort
Topological sort
 
Lecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfLecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdf
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning tree
 
Data Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docxData Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docx
 
FADML 06 PPC Graphs and Traversals.pdf
FADML 06 PPC Graphs and Traversals.pdfFADML 06 PPC Graphs and Traversals.pdf
FADML 06 PPC Graphs and Traversals.pdf
 
Chapter3 Search
Chapter3 SearchChapter3 Search
Chapter3 Search
 
Dfs presentation
Dfs presentationDfs presentation
Dfs presentation
 
Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7
 
Graps 2
Graps 2Graps 2
Graps 2
 
Link Prediction in the Real World
Link Prediction in the Real WorldLink Prediction in the Real World
Link Prediction in the Real World
 
Unit ii-ppt
Unit ii-pptUnit ii-ppt
Unit ii-ppt
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structures
 

More from Shakil Ahmed

More from Shakil Ahmed (20)

B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-tree
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Command pattern
Command patternCommand pattern
Command pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
iOS 5
iOS 5iOS 5
iOS 5
 
Ios development
Ios developmentIos development
Ios development
 
Lowest common ancestor
Lowest common ancestorLowest common ancestor
Lowest common ancestor
 
Segment tree
Segment treeSegment tree
Segment tree
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Trie tree
Trie treeTrie tree
Trie tree
 

Recently uploaded

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Graph

  • 1. Graph Md. Shakil Ahmed Software Engineer Astha it research & consultancy ltd. Dhaka, Bangladesh
  • 2. Introduction Topic Focus: • Graph Representation • DFS • BFS • Union Find • Kruskal's algorithm • Floyd-Warshall's Algorithm • Dijkstra's Algorithm • Bipartite graph
  • 3. Graph a) An undirected graph and (b) a directed graph.
  • 4. Definitions and Representation An undirected graph and its adjacency matrix representation. An undirected graph and its adjacency list representation.
  • 5. Depth-First Search • Depth-first search is a systematic way to find all the vertices reachable from a source vertex, s. • Historically, depth-first was first stated formally hundreds of years ago as a method for traversing mazes. • The basic idea of depth-first search is this: It methodically explore every edge. We start over from different vertices as necessary. As soon as we discover a vertex, DFS starts exploring from it
  • 7.
  • 8. Depth-First Search procedure DFS(G,v): label v as explored for all edges e in G.incidentEdges(v) do if edge e is unexplored then w ← G.opposite(v,e) if vertex w is unexplored then label e as a discovery edge recursively call DFS(G,w)
  • 9. DFS Source Code void DFS(long node) { long i; printf(“%ld “,node); visit[node]=1; for(i=1;i<=n;i++) if(visit[i]==0&&A[node][i]==1) DFS(i); } visit[]={0}; A[][] = connection matrix. n = number of nodes, from 1 to n. source = 1; DFS(source);
  • 10. Sample • UVA Online Judge: 260, 352, 469, 572, 776, 784, 871, 1197, 10336, 10946, 11110, 11244, 11470, 11518.
  • 11. Breadth-first search • In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. • Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal. 11
  • 14. BFS Pseudo-Code Step 1: Initialize all nodes to ready state (status = 1) Step 2: Put the starting node in queue and change its status to the waiting state (status = 2) Step 3: Repeat step 4 and 5 until queue is empty Step 4: Remove the front node n of queue. Process n and change the status of n to the processed state (status = 3) Step 5: Add to the rear of the queue all the neighbors of n that are in ready state (status = 1), and change their status to the waiting state (status = 2). [End of the step 3 loop] Step 6: Exit 14
  • 15. BFS Source Code } visit[]={0}; N++; A[][] = connection matrix. } n = number of nodes, from 1 to n. for(i=0;i<M;i++) source = 1; printf(“%ld “,temp[i]); temp[0]=source; visit[ source ]=1; N = 0; M = 1; while(N!=M) { for(i=1;i<=n;i++) if(A[temp[N]][i]==1&&visit[i]==0) { visit[i]=1; temp[M]=i; M++;
  • 16. Sample • UVA Online Judge: 336, 383, 429, 439, 532, 567, 627, 762, 924, 10009, 10067, 10422, 10610, 10653, 10959, 10977, 11049, 11101, 11352, 11624, 11974, 12160.
  • 17. DFS vs. BFS DFS Process F B A start E G D C destination C DFS on C D Call DFS on D B DFS on B B B Return to call on B A DFS on A A A A G Call DFS on G found destination - done! Path is implicitly stored in DFS recursion D Path is: A, B, D, G B A
  • 18. DFS vs. BFS F B A start E BFS Process G D C destination rear front rear front rear front rear front A B D C D Initial call to BFS on A Dequeue A Dequeue B Dequeue C Add A to queue Add B Add C, D Nothing to add rear front G found destination - done! Path must be stored separately Dequeue D Add G
  • 19. Union Find • Union Find is an algorithm which uses a disjoint-set data structure to solve the following problem: Say we have some number of items. We are allowed to merge any two items to consider them equal (where equality here obeys all of the properties of an Equivalence Relation). At any point, we are allowed to ask whether two items are considered equal or not. • Basically a Union Find data structure implements two functions: 1. union( A, B ) - merge A's set with B's set 2. find( A ) - finds what set A belongs to
  • 21. Union Find Pseudocode func find( var element ) while ( element is not the root ) element = element's parent return element end func func union( var setA, var setB ) var rootA = find( setA ) rootB = find( setB ) if ( rootA is equal to rootB ) return else set rootB as rootA's parent end func
  • 23. Union Find Source Code long Parent(long h1) { if(P[h1]==-1) To find, any two members return h1; are same or different group P[h1] = Parent(P[h1]); for(i=1;i<=k;i++) return P[h1]; { scanf(“%ld %ld”,&x,&y); } x1 = Parent(x); for(i=1;i<=n;i++) // n number of thing y1 = Parent(y); P[i]=-1; if(x1!=y1) for(i=1;i<=m;i++) // m number of connection printf(“Differentn”); else { printf(“Samen”); scanf(“%ld %ld”,&x,&y); } x1 = Parent(x); y1 = Parent(y); if(x1!=y1) P[x1]=y1; }
  • 24. Sample • UVA Online Judge: 459, 793, 10158, 10369, 10583, 10608, 10685, 11503.
  • 25. Minimum Spanning Tree • A spanning tree of an undirected graph G is a subgraph of G that is a tree containing all the vertices of G. • In a weighted graph, the weight of a subgraph is the sum of the weights of the edges in the subgraph. • A minimum spanning tree (MST) for a weighted undirected graph is a spanning tree with minimum weight.
  • 26. Minimum Spanning Tree An undirected graph and its minimum spanning tree.
  • 27. Kruskal's algorithm • Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. If the graph is not connected, then it finds a minimum spanning forest (a minimum spanning tree for each connected component). • Kruskal's algorithm is an example of a greedy algorithm.
  • 28. Kruskal's algorithm Pseudocode 1 (Sort the edges in an increasing order) 2 A:={} 3 while E is not empty do { 3 take an edge (u, v) that is shortest in E and delete it from E 4 if u and v are in different components then add (u, v) to A } 28
  • 29. The execution of Kruskal's algorithm (Moderate part) •The edges are considered by the algorithm in sorted order by weight. •The edge under consideration at each step is shown with a red weight number. 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 29
  • 30. 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 30
  • 31. 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 31
  • 32. 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 32
  • 33. 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 33
  • 34. 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 8 7 b c d 9 4 2 a 11 14 e i 4 7 6 10 8 h g f 1 2 34
  • 35. Kruskal's algorithm Source Code for(i=1;i<=n;i++) // n number of node struct T P[i]=-1; { for(i=0;i<m;i++) // m number of edge long x; scanf(“%ld %ld long y; %ld”,&a[i].x,&a[i].y,&a[i].weight); long weight; qsort(a,m,sizeof(T),cmp); }; cost = 0; for(i=0;i<m;i++) T a[1000009]; { int cmp( const void *a, const void *b ) x = Parent(a[i].x); { y = Parent(a[i].y); T *p = (T *)a; if(x!=y) T *q = (T *)b; { cost+=a[i].weight; return ( p->weight – q->weight ); P[x]=y; } } } printf(“%ldn”,cost);
  • 36. Sample • UVA Online Judge: 544, 908, 10034, 10369, 10048, 10147, 10397, 10600, 10842, 11631, 11710, 11747.
  • 37. Floyd-Warshall's Algorithm • The Floyd-Warshall Algorithm is an efficient algorithm to find all-pairs shortest paths on a graph. • That is, it is guaranteed to find the shortest path between every pair of vertices in a graph. • The graph may have negative weight edges, but no negative weight cycles (for then the shortest path is undefined).
  • 38. Floyd-Warshall for (int k = 1; k =< V; k++) for (int i = 1; i =< V; i++) for (int j = 1; j =< V; j++) if ( ( M[i][k]+ M[k][j] ) < M[i][j] ) M[i][j] = M[i][k]+ M[k][j] Invariant: After the kth iteration, the matrix includes the shortest paths for all pairs of vertices (i,j) containing only vertices 1..k as intermediate vertices
  • 39. a 2 b -2 Initial state of the 1 -4 3 c matrix: d 1 e a b c d e 4 a 0 2 - -4 - b - 0 -2 1 3 c - - 0 - 1 d - - - 0 4 e - - - - 0 M[i][j] = min(M[i][j], M[i][k]+ M[k][j])
  • 40. a 2 b -2 Floyd-Warshall - for 1 All-pairs shortest -4 3 c path d 1 e 4 a b c d e a 0 2 0 -4 0 b - 0 -2 1 -1 Final Matrix Contents c - - 0 - 1 d - - - 0 4 e - - - - 0
  • 41. Sample • UVA Online Judge: 104, 125, 186, 436, 523, 821, 10075, 10171, 10793, 10803, 11015.
  • 42. Single-Source Shortest Paths • For a weighted graph G = (V,E,w), the single- source shortest paths problem is to find the shortest paths from a vertex v ∈ V to all other vertices in V. • Dijkstra's algorithm maintains a set of nodes for which the shortest paths are known. • It grows this set based on the node closest to source using one of the nodes in the current shortest path set.
  • 43. Single-Source Shortest Paths: Dijkstra's Algorithm function Dijkstra(Graph, source) for each vertex v in Graph: // Initializations dist[v] := infinity ; previous[v] := undefined ; end for ; dist[source] := 0 ; Q := the set of all nodes in Graph ; while Q is not empty: u := vertex in Q with smallest distance in dist[] ; if dist[u] = infinity: break ; end if ;
  • 44. remove u from Q ; for each neighbor v of u: alt := dist[u] + dist_between(u, v) ; if alt < dist[v]: dist[v] := alt ; previous[v] := u ; end if ; end for ; end while ; return dist[] ; end Dijkstra.
  • 45. Example u v 1 ∞ ∞ 10 9 2 3 s 0 4 6 5 7 ∞ ∞ 2 x y Comp 122, Fall 2003 Single-source SPs - 45
  • 46. Example u v 1 10 ∞ 10 9 2 3 s 0 4 6 5 7 5 ∞ 2 x y Comp 122, Fall 2003 Single-source SPs - 46
  • 47. Example u v 1 8 14 10 9 2 3 s 0 4 6 5 7 5 7 2 x y Comp 122, Fall 2003 Single-source SPs - 47
  • 48. Example u v 1 8 13 10 9 2 3 s 0 4 6 5 7 5 7 2 x y Comp 122, Fall 2003 Single-source SPs - 48
  • 49. Example u v 1 8 9 10 9 2 3 s 0 4 6 5 7 5 7 2 x y Comp 122, Fall 2003 Single-source SPs - 49
  • 50. Example u v 1 8 9 10 9 2 3 s 0 4 6 5 7 5 7 2 x y Comp 122, Fall 2003 Single-source SPs - 50
  • 51. Dijkstra Source Code #include <cstdio> vector< pii > G[MAX]; int D[MAX]; #include <queue> bool F[MAX]; #include <vector> vector< pii > G[MAX]; using namespace std; int D[MAX]; #define MAX 100001 bool F[MAX]; #define INF (1<<20) #define DEBUG if(0) #define pii pair< int, int > #define pb(x) push_back(x) struct comp { bool operator() (const pii &a, const pii &b) { return a.second > b.second; } }; priority_queue< pii, vector< pii >, comp > Q;
  • 52. if(F[u]) continue; int main() { sz = G[u].size(); int i, u, v, w, sz, nodes, edges, starting; for(i=0; i<sz; i++) { scanf("%d %d", &nodes, &edges); v = G[u][i].first; for(i=0; i<edges; i++) { w = G[u][i].second; scanf("%d %d %d", &u, &v, &w); if(!F[v] && D[u]+w < D[v]) { G[u].pb(pii(v, w)); D[v] = D[u] + w; Q.push(pii(v, D[v])); G[v].pb(pii(u, w)); // for } undirected } } scanf("%d", &starting); F[u] = 1; // done with u for(i=1; i<=nodes; i++) D[i] = INF; } D[starting] = 0; for(i=1; i<=nodes; i++) Q.push(pii(starting, 0)); printf("Node %d, min weight = %dn", i, // dijkstra D[i]); while(!Q.empty()) { return 0; u = Q.top().first; } Q.pop();
  • 53. Sample • UVA Online Judge: 10986, 423, 10801, 10917, 10986, 11338, 11813.
  • 54. Bipartite graph • In the mathematical field of graph theory, a bipartite graph (or bigraph) is a graph whose vertices can be divided into two disjoint sets U and V such that every edge connects a vertex in U to one in V; that is, U and V are independent sets. Equivalently, a bipartite graph is a graph that does not contain any odd- length cycles. • We can use bfs or dfs for checking Bipartite graph.
  • 55. Bipartite graph Using DFS void BiColor(long node) color[]={-1}; { A[][] = connection matrix. long i; n = number of nodes, from 1 to n. yes = 1; for(i=1;i<=n;i++) for(i=1;i<=n;i++) if(A[node][i]==1) if(color[i]==-1) { { if(color[i]==-1) color[i]=0; { BiColor(i); color[i] = (color[node] + 1 )%2; } BiColor(i); if(yes==1) } printf(“possiblen”); else if(color[i]==color[node]) else yes = 0; printf(“not possiblen”); if(yes==0) break; } }
  • 56. Sample • UVA Online Judge: 10004, 11080, 11396.