SlideShare a Scribd company logo
Lecture 11:
     Breadth-First Search
         Steven Skiena

Department of Computer Science
 State University of New York
 Stony Brook, NY 11794–4400

http://www.cs.sunysb.edu/∼skiena
Problem of the Day
Present correct and efficient algorithms to convert between
the following graph data structures, for an undirected graph
G with n vertices and m edges. You must give the time
complexity of each algorithm.
1. Convert from an adjacency matrix to adjacency lists.
2. Convert from an adjacency list to an incidence matrix.
   An incidence matrix M has a row for each vertex and a
   column for each edge, such that M [i, j] = 1 if vertex i is
   part of edge j, otherwise M [i, j] = 0.
3. Convert from an incidence matrix to adjacency lists.
Traversing a Graph
One of the most fundamental graph problems is to traverse
every edge and vertex in a graph.
For efficiency, we must make sure we visit each edge at most
twice.
For correctness, we must do the traversal in a systematic way
so that we don’t miss anything.
Since a maze is just a graph, such an algorithm must be
powerful enough to enable us to get out of an arbitrary maze.
Marking Vertices
The key idea is that we must mark each vertex when we
first visit it, and keep track of what have not yet completely
explored.
Each vertex will always be in one of the following three
states:
 • undiscovered – the vertex in its initial, virgin state.
 • discovered – the vertex after we have encountered it, but
   before we have checked out all its incident edges.
 • processed – the vertex after we have visited all its incident
   edges.
Obviously, a vertex cannot be processed before we discover
it, so over the course of the traversal the state of each vertex
progresses from undiscovered to discovered to processed.
To Do List
We must also maintain a structure containing all the vertices
we have discovered but not yet completely explored.
Initially, only a single start vertex is considered to be
discovered.
To completely explore a vertex, we look at each edge going
out of it. For each edge which goes to an undiscovered vertex,
we mark it discovered and add it to the list of work to do.
Note that regardless of what order we fetch the next vertex to
explore, each edge is considered exactly twice, when each of
its endpoints are explored.
Correctness of Graph Traversal
Every edge and vertex in the connected component is
eventually visited.
Suppose not, ie. there exists a vertex which was unvisited
whose neighbor was visited. This neighbor will eventually be
explored so we would visit it:
Breadth-First Traversal
The basic operation in most graph algorithms is completely
and systematically traversing the graph. We want to visit
every vertex and every edge exactly once in some well-
defined order.
Breadth-first search is appropriate if we are interested in
shortest paths on unweighted graphs.
Data Structures for BFS
We use two Boolean arrays to maintain our knowledge about
each vertex in the graph.
A vertex is discovered the first time we visit it.
A vertex is considered processed after we have traversed
all outgoing edges from it.
Once a vertex is discovered, it is placed on a FIFO queue.
Thus the oldest vertices / closest to the root are expanded first.
bool processed[MAXV];
bool discovered[MAXV];
int parent[MAXV];
Initializing BFS

initialize search(graph *g)
{
       int i;

      for (i=1; i<=g− >nvertices; i++) {
             processed[i] = discovered[i] = FALSE;
             parent[i] = -1;
      }
}
BFS Implementation

bfs(graph *g, int start)
{
      queue q;
      int v;
      int y;
      edgenode *p;

      init queue(&q);
      enqueue(&q,start);
      discovered[start] = TRUE;

      while (empty queue(&q) == FALSE) {
            v = dequeue(&q);
            process vertex early(v);
            processed[v] = TRUE;
            p = g− >edges[v];
            while (p ! = NULL) {
                  y = p− >y;
                  if ((processed[y] == FALSE) || g− >directed)
                         process edge(v,y);
                  if (discovered[y] == FALSE) {
enqueue(&q,y);
                    discovered[y] = TRUE;
                    parent[y] = v;
              }
              p = p− >next;
        }
        process vertex late(v);
    }
}
BFS Example

                  2
                          3           1

          1
                                  2   5   6
                              4


                      5           3   4
              6
Exploiting Traversal
We can easily customize what the traversal does as it makes
one official visit to each edge and each vertex. By setting the
functions to
process vertex(int v)
{
      printf(”processed vertex %d ”,v);
}

process edge(int x, int y)
{
      printf(”processed edge (%d,%d) ”,x,y);
}



we print each vertex and edge exactly once.
Finding Paths
The parent array set within bfs() is very useful for
finding interesting paths through a graph.
The vertex which discovered vertex i is defined as
parent[i].
The parent relation defines a tree of discovery with the initial
search node as the root of the tree.
Shortest Paths and BFS
In BFS vertices are discovered in order of increasing distance
from the root, so this tree has a very important property.
The unique tree path from the root to any node x ∈ V uses
the smallest number of edges (or equivalently, intermediate
nodes) possible on any root-to-x path in the graph.
Recursion and Path Finding
We can reconstruct this path by following the chain of
ancestors from x to the root. Note that we have to work
backward. We cannot find the path from the root to x,
since that does not follow the direction of the parent pointers.
Instead, we must find the path from x to the root.
find path(int start, int end, int parents[])
{
     if ((start == end) || (end == -1))
             printf(”%d”,start);
     else {
             find path(start,parents[end],parents);
             printf(” %d”,end);
     }
}
Connected Components
The connected components of an undirected graph are the
separate “pieces” of the graph such that there is no connection
between the pieces.
Many seemingly complicated problems reduce to finding
or counting connected components. For example, testing
whether a puzzle such as Rubik’s cube or the 15-puzzle can
be solved from any position is really asking whether the graph
of legal configurations is connected.
Anything we discover during a BFS must be part of the
same connected component. We then repeat the search from
any undiscovered vertex (if one exists) to define the next
component, until all vertices have been found:
Implementation

connected components(graph *g)
{
     int c;
     int i;

     initialize search(g);

     c = 0;
     for (i=1; i<=g− >nvertices; i++)
            if (discovered[i] == FALSE) {
                   c = c+1;
                   printf(”Component %d:”,c);
                   bfs(g,i);
            }
}
Two-Coloring Graphs
The vertex coloring problem seeks to assign a label (or color)
to each vertex of a graph such that no edge links any two
vertices of the same color.
A graph is bipartite if it can be colored without conflicts while
using only two colors. Bipartite graphs are important because
they arise naturally in many applications.
For example, consider the “had-sex-with” graph in a hetero-
sexual world. Men have sex only with women, and vice versa.
Thus gender defines a legal two-coloring.
Finding a Two-Coloring
We can augment breadth-first search so that whenever we
discover a new vertex, we color it the opposite of its parent.
twocolor(graph *g)
{
     int i;

     for (i=1; i<=(g− >nvertices); i++)
            color[i] = UNCOLORED;

     bipartite = TRUE;

     initialize search(&g);

     for (i=1; i<=(g− >nvertices); i++)
            if (discovered[i] == FALSE) {
                   color[i] = WHITE;
                   bfs(g,i);
            }
}
process edge(int x, int y)
{
      if (color[x] == color[y]) {
             bipartite = FALSE;
             printf(”Warning: graph not bipartite, due to (%d,%d)”,x,y);
      }

      color[y] = complement(color[x]);
}


complement(int color)
{
if (color == WHITE) return(BLACK);
if (color == BLACK) return(WHITE);

return(UNCOLORED);
}



We can assign the first vertex in any connected component to
be whatever color/sex we wish.

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 search
Hossain Md Shakhawat
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
Jaya Gautam
 
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
 
130210107039 2130702
130210107039 2130702130210107039 2130702
130210107039 2130702
Ketaki_Pattani
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
Praveen Yadav
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
Sazzad Hossain
 
Bfs & dfs application
Bfs & dfs applicationBfs & dfs application
Bfs & dfs application
Umme habiba
 
Bfs dfs
Bfs dfsBfs dfs
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
DEEPIKA T
 
Graph
GraphGraph
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
Benjamin Sach
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
Rajandeep Gill
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
Masud Parvaze
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02
Krish_ver2
 
Depth-First Search
Depth-First SearchDepth-First Search
Depth-First Search
Md. Shafiuzzaman Hira
 
lecture 17
lecture 17lecture 17
lecture 17
sajinsc
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
hansa khan
 
Topological Sort
Topological SortTopological Sort
Topological Sort
Dr Sandeep Kumar Poonia
 
Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8
Traian Rebedea
 
Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12
Traian Rebedea
 

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
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
130210107039 2130702
130210107039 2130702130210107039 2130702
130210107039 2130702
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
 
Bfs & dfs application
Bfs & dfs applicationBfs & dfs application
Bfs & dfs application
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
Graph
GraphGraph
Graph
 
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
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02
 
Depth-First Search
Depth-First SearchDepth-First Search
Depth-First Search
 
lecture 17
lecture 17lecture 17
lecture 17
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8
 
Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12
 

Similar to Skiena algorithm 2007 lecture11 breadth deapth first search

Graphs
GraphsGraphs
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
lalithambiga kamaraj
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Graps 2
Graps 2Graps 2
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
whittemorelucilla
 
Graph applications chapter
Graph applications chapterGraph applications chapter
Graph applications chapter
Savit Chandra
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
bashirabdullah789
 
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
zukun
 
DATA STRUCTURES.pptx
DATA STRUCTURES.pptxDATA STRUCTURES.pptx
DATA STRUCTURES.pptx
KENNEDY GITHAIGA
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
PyData
 
logic.pptx
logic.pptxlogic.pptx
logic.pptx
KENNEDY GITHAIGA
 
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
ChristianKapsales1
 
Graphs
GraphsGraphs
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
Muhammad Danish Badar
 
Graphs.ppt
Graphs.pptGraphs.ppt
Graphs.ppt
lakshmi26355
 
Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt of mathemaics  we have to clar all doubtsGraphs.ppt of mathemaics  we have to clar all doubts
Graphs.ppt of mathemaics we have to clar all doubts
nc3186331
 
Chap04alg
Chap04algChap04alg
Chap04alg
Munhchimeg
 
Chap04alg
Chap04algChap04alg
Chap04alg
Munkhchimeg
 
Graph Traversal Algorithms - Depth First Search Traversal
Graph Traversal Algorithms - Depth First Search TraversalGraph Traversal Algorithms - Depth First Search Traversal
Graph Traversal Algorithms - Depth First Search Traversal
Amrinder Arora
 
Graphs
GraphsGraphs

Similar to Skiena algorithm 2007 lecture11 breadth deapth first search (20)

Graphs
GraphsGraphs
Graphs
 
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Graps 2
Graps 2Graps 2
Graps 2
 
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
 
Graph applications chapter
Graph applications chapterGraph applications chapter
Graph applications chapter
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
 
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
 
DATA STRUCTURES.pptx
DATA STRUCTURES.pptxDATA STRUCTURES.pptx
DATA STRUCTURES.pptx
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
 
logic.pptx
logic.pptxlogic.pptx
logic.pptx
 
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
 
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
 
Graphs.ppt
Graphs.pptGraphs.ppt
Graphs.ppt
 
Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt of mathemaics  we have to clar all doubtsGraphs.ppt of mathemaics  we have to clar all doubts
Graphs.ppt of mathemaics we have to clar all doubts
 
Chap04alg
Chap04algChap04alg
Chap04alg
 
Chap04alg
Chap04algChap04alg
Chap04alg
 
Graph Traversal Algorithms - Depth First Search Traversal
Graph Traversal Algorithms - Depth First Search TraversalGraph Traversal Algorithms - Depth First Search Traversal
Graph Traversal Algorithms - Depth First Search Traversal
 
Graphs
GraphsGraphs
Graphs
 

More from zukun

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009
zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
zukun
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Information
zukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statistics
zukun
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
zukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
zukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluation
zukun
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-software
zukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptors
zukun
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectors
zukun
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-intro
zukun
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video search
zukun
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video search
zukun
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video search
zukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
zukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
zukun
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick start
zukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
zukun
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structures
zukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
zukun
 

More from zukun (20)

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Information
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statistics
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluation
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-software
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptors
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectors
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-intro
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video search
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video search
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video search
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick start
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structures
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
 

Recently uploaded

What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 

Recently uploaded (20)

What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 

Skiena algorithm 2007 lecture11 breadth deapth first search

  • 1. Lecture 11: Breadth-First Search Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794–4400 http://www.cs.sunysb.edu/∼skiena
  • 2. Problem of the Day Present correct and efficient algorithms to convert between the following graph data structures, for an undirected graph G with n vertices and m edges. You must give the time complexity of each algorithm. 1. Convert from an adjacency matrix to adjacency lists.
  • 3. 2. Convert from an adjacency list to an incidence matrix. An incidence matrix M has a row for each vertex and a column for each edge, such that M [i, j] = 1 if vertex i is part of edge j, otherwise M [i, j] = 0. 3. Convert from an incidence matrix to adjacency lists.
  • 4. Traversing a Graph One of the most fundamental graph problems is to traverse every edge and vertex in a graph. For efficiency, we must make sure we visit each edge at most twice. For correctness, we must do the traversal in a systematic way so that we don’t miss anything. Since a maze is just a graph, such an algorithm must be powerful enough to enable us to get out of an arbitrary maze.
  • 5. Marking Vertices The key idea is that we must mark each vertex when we first visit it, and keep track of what have not yet completely explored. Each vertex will always be in one of the following three states: • undiscovered – the vertex in its initial, virgin state. • discovered – the vertex after we have encountered it, but before we have checked out all its incident edges. • processed – the vertex after we have visited all its incident edges.
  • 6. Obviously, a vertex cannot be processed before we discover it, so over the course of the traversal the state of each vertex progresses from undiscovered to discovered to processed.
  • 7. To Do List We must also maintain a structure containing all the vertices we have discovered but not yet completely explored. Initially, only a single start vertex is considered to be discovered. To completely explore a vertex, we look at each edge going out of it. For each edge which goes to an undiscovered vertex, we mark it discovered and add it to the list of work to do. Note that regardless of what order we fetch the next vertex to explore, each edge is considered exactly twice, when each of its endpoints are explored.
  • 8. Correctness of Graph Traversal Every edge and vertex in the connected component is eventually visited. Suppose not, ie. there exists a vertex which was unvisited whose neighbor was visited. This neighbor will eventually be explored so we would visit it:
  • 9. Breadth-First Traversal The basic operation in most graph algorithms is completely and systematically traversing the graph. We want to visit every vertex and every edge exactly once in some well- defined order. Breadth-first search is appropriate if we are interested in shortest paths on unweighted graphs.
  • 10. Data Structures for BFS We use two Boolean arrays to maintain our knowledge about each vertex in the graph. A vertex is discovered the first time we visit it. A vertex is considered processed after we have traversed all outgoing edges from it. Once a vertex is discovered, it is placed on a FIFO queue. Thus the oldest vertices / closest to the root are expanded first. bool processed[MAXV]; bool discovered[MAXV]; int parent[MAXV];
  • 11. Initializing BFS initialize search(graph *g) { int i; for (i=1; i<=g− >nvertices; i++) { processed[i] = discovered[i] = FALSE; parent[i] = -1; } }
  • 12. BFS Implementation bfs(graph *g, int start) { queue q; int v; int y; edgenode *p; init queue(&q); enqueue(&q,start); discovered[start] = TRUE; while (empty queue(&q) == FALSE) { v = dequeue(&q); process vertex early(v); processed[v] = TRUE; p = g− >edges[v]; while (p ! = NULL) { y = p− >y; if ((processed[y] == FALSE) || g− >directed) process edge(v,y); if (discovered[y] == FALSE) {
  • 13. enqueue(&q,y); discovered[y] = TRUE; parent[y] = v; } p = p− >next; } process vertex late(v); } }
  • 14. BFS Example 2 3 1 1 2 5 6 4 5 3 4 6
  • 15. Exploiting Traversal We can easily customize what the traversal does as it makes one official visit to each edge and each vertex. By setting the functions to process vertex(int v) { printf(”processed vertex %d ”,v); } process edge(int x, int y) { printf(”processed edge (%d,%d) ”,x,y); } we print each vertex and edge exactly once.
  • 16. Finding Paths The parent array set within bfs() is very useful for finding interesting paths through a graph. The vertex which discovered vertex i is defined as parent[i]. The parent relation defines a tree of discovery with the initial search node as the root of the tree.
  • 17. Shortest Paths and BFS In BFS vertices are discovered in order of increasing distance from the root, so this tree has a very important property. The unique tree path from the root to any node x ∈ V uses the smallest number of edges (or equivalently, intermediate nodes) possible on any root-to-x path in the graph.
  • 18. Recursion and Path Finding We can reconstruct this path by following the chain of ancestors from x to the root. Note that we have to work backward. We cannot find the path from the root to x, since that does not follow the direction of the parent pointers. Instead, we must find the path from x to the root. find path(int start, int end, int parents[]) { if ((start == end) || (end == -1)) printf(”%d”,start); else { find path(start,parents[end],parents); printf(” %d”,end); } }
  • 19. Connected Components The connected components of an undirected graph are the separate “pieces” of the graph such that there is no connection between the pieces. Many seemingly complicated problems reduce to finding or counting connected components. For example, testing whether a puzzle such as Rubik’s cube or the 15-puzzle can be solved from any position is really asking whether the graph of legal configurations is connected. Anything we discover during a BFS must be part of the same connected component. We then repeat the search from any undiscovered vertex (if one exists) to define the next component, until all vertices have been found:
  • 20. Implementation connected components(graph *g) { int c; int i; initialize search(g); c = 0; for (i=1; i<=g− >nvertices; i++) if (discovered[i] == FALSE) { c = c+1; printf(”Component %d:”,c); bfs(g,i); } }
  • 21. Two-Coloring Graphs The vertex coloring problem seeks to assign a label (or color) to each vertex of a graph such that no edge links any two vertices of the same color. A graph is bipartite if it can be colored without conflicts while using only two colors. Bipartite graphs are important because they arise naturally in many applications. For example, consider the “had-sex-with” graph in a hetero- sexual world. Men have sex only with women, and vice versa. Thus gender defines a legal two-coloring.
  • 22. Finding a Two-Coloring We can augment breadth-first search so that whenever we discover a new vertex, we color it the opposite of its parent. twocolor(graph *g) { int i; for (i=1; i<=(g− >nvertices); i++) color[i] = UNCOLORED; bipartite = TRUE; initialize search(&g); for (i=1; i<=(g− >nvertices); i++) if (discovered[i] == FALSE) { color[i] = WHITE; bfs(g,i); } }
  • 23. process edge(int x, int y) { if (color[x] == color[y]) { bipartite = FALSE; printf(”Warning: graph not bipartite, due to (%d,%d)”,x,y); } color[y] = complement(color[x]); } complement(int color) { if (color == WHITE) return(BLACK); if (color == BLACK) return(WHITE); return(UNCOLORED); } We can assign the first vertex in any connected component to be whatever color/sex we wish.