Graph Search Computing 2 COMP1927 15s1. P ROBLEMS ON G RAPHS What kinds of problems do we want to solve on/via graphs? Is there a simple path from A to.

Slides:



Advertisements
Similar presentations
Review Binary Search Trees Operations on Binary Search Tree
Advertisements

Graphs CSC 220 Data Structure. Introduction One of the Most versatile data structures like trees. Terminology –Nodes in trees are vertices in graphs.
1 Graphs Traversals In many graph problems, we need to traverse the vertices of the graph in some order Analogy: Binary tree traversals –Pre-order Traversal.
Graph Theory, DFS & BFS Kelly Choi What is a graph? A set of vertices and edges –Directed/Undirected –Weighted/Unweighted –Cyclic/Acyclic.
More Graphs COL 106 Slides from Naveen. Some Terminology for Graph Search A vertex is white if it is undiscovered A vertex is gray if it has been discovered.
Graph Searching CSE 373 Data Structures Lecture 20.
Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u
TECH Computer Science Graphs and Graph Traversals  // From Tree to Graph  // Many programs can be cast as problems on graph Definitions and Representations.
Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u
Graphs Chapter 12. Chapter Objectives  To become familiar with graph terminology and the different types of graphs  To study a Graph ADT and different.
Breadth-First and Depth-First Search
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Graph Search Methods Spring 2007 CSE, POSTECH. Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u. A search method.
Graph Searching (Graph Traversal) Algorithm Design and Analysis Week 8 Bibliography: [CLRS] – chap 22.2 –
Graph Traversals Visit vertices of a graph G to determine some property: Is G connected? Is there a path from vertex a to vertex b? Does G have a cycle?
Data Structures & Algorithms Graph Search Richard Newman based on book by R. Sedgewick and slides by S. Sahni.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Graph COMP171 Fall Graph / Slide 2 Graphs * Extremely useful tool in modeling problems * Consist of: n Vertices n Edges D E A C F B Vertex Edge.
1 Data Structures and Algorithms Graphs I: Representation and Search Gal A. Kaminka Computer Science Department.
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
Spring 2010CS 2251 Graphs Chapter 10. Spring 2010CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
Breadth First Search (BFS) Part 2 COMP171. Graph / Slide 2 Shortest Path Recording * BFS we saw only tells us whether a path exists from source s, to.
Fall 2007CS 2251 Graphs Chapter 12. Fall 2007CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs To.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
CISC220 Fall 2009 James Atlas Nov 13: Graphs, Line Intersections.
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Review of Graphs A graph is composed of edges E and vertices V that link the nodes together. A graph G is often denoted G=(V,E) where V is the set of vertices.
IS 2610: Data Structures Graph April 5, 2004.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
Search Related Algorithms. Graph Code Adjacency List Representation:
Tree Searching Breadth First Search Dept First Search.
Chapter 2 Graph Algorithms.
COSC 2007 Data Structures II Chapter 14 Graphs III.
Data Structures and Algorithms Ver. 1.0 Session 17 Objectives In this session, you will learn to: Implement a graph Apply graphs to solve programming problems.
1 Applications of BFS and DFS CSE 2011 Winter May 2016.
Elementary Graph Algorithms CLRS Chapter 22. Graph A graph is a structure that consists of a set of vertices and a set of edges between pairs of vertices.
Graphs. Definitions A graph is two sets. A graph is two sets. –A set of nodes or vertices V –A set of edges E Edges connect nodes. Edges connect nodes.
D ESIGN & A NALYSIS OF A LGORITHM 04 – G RAPH A LGORITHMS Informatics Department Parahyangan Catholic University.
10 Copyright © William C. Cheng Data Structures - CSCI 102 Graph Terminology A graph consists of a set of Vertices and a set of Edges C A B D a c b d e.
Most of contents are provided by the website Graph Essentials TJTSD66: Advanced Topics in Social Media.
1 Chapter 22 Elementary Graph Algorithms. 2 Introduction G=(V, E) –V = vertex set –E = edge set Graph representation –Adjacency list –Adjacency matrix.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
1 Subgraphs A subgraph S of a graph G is a graph such that The vertices of S are a subset of the vertices of G The edges of S are a subset of the edges.
Weighted Graphs Computing 2 COMP s1 Sedgewick Part 5: Chapter
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between.
Trees, Binary Search Trees, Balanced Trees, Graphs Graph Fundamentals Telerik Algo Academy
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
COSC 2007 Data Structures II
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
7. Graph Traversal Describe and compare depth-first and breadth-first graph searching, and look at the creation of spanning trees Contest Algorithms: 7.
Graphs & Paths Presentation : Part II. Graph representation Given graph G = (V, E). May be either directed or undirected. Two common ways to represent.
Shahed University Dr. Shahriar Bijani May  A path is a sequence of vertices P = (v 0, v 1, …, v k ) such that, for 1 ≤ i ≤ k, edge (v i – 1, v.
Graphs and Paths : Chapter 15 Saurav Karmakar
Chapter 05 Introduction to Graph And Search Algorithms.
Graphs + Shortest Paths David Kauchak cs302 Spring 2013.
Graph Searching CSIT 402 Data Structures II. 2 Graph Searching Methodology Depth-First Search (DFS) Depth-First Search (DFS) ›Searches down one path as.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
GRAPH ALGORITHM. Graph A pair G = (V,E) – V = set of vertices (node) – E = set of edges (pairs of vertices) V = (1,2,3,4,5,6,7) E = ( (1,2),(2,3),(3,5),(1,4),(4,5),(6,7)
1 GRAPHS – Definitions A graph G = (V, E) consists of –a set of vertices, V, and –a set of edges, E, where each edge is a pair (v,w) s.t. v,w  V Vertices.
Graphs. What is a graph? In simple words, A graph is a set of vertices and edges which connect them. A node (or vertex) is a discrete position in the.
Nattee Niparnan. Graph  A pair G = (V,E)  V = set of vertices (node)  E = set of edges (pairs of vertices)  V = (1,2,3,4,5,6,7)  E = ((1,2),(2,3),(3,5),(1,4),(4,
Brute Force and Exhaustive Search Brute Force and Exhaustive Search Traveling Salesman Problem Knapsack Problem Assignment Problem Selection Sort and Bubble.
Code: BCA302 Data Structures with C Prof. (Dr.) Monalisa Banerjee By.
Brute Force and Exhaustive Search Brute Force and Exhaustive Search Traveling Salesman Problem Knapsack Problem Assignment Problem Selection Sort and Bubble.
Review Graph Directed Graph Undirected Graph Sub-Graph Spanning Sub-Graph Degree of a Vertex Weighted Graph Elementary and Simple Path Link List Representation.
Lectures on Graph Algorithms: searching, testing and sorting
Elementary Graph Algorithms
Chapter 11 Graphs.
Presentation transcript:

Graph Search Computing 2 COMP s1

P ROBLEMS ON G RAPHS What kinds of problems do we want to solve on/via graphs? Is there a simple path from A to B Is the graph fully-connected? Can we remove an edge and keep it fully connected? Which vertices are reachable from v? (transitive closure) What is the cheapest cost path from v to w? Is there a cycle that passes through all V? (tour) Is there a tree that links all vertices (spanning tree) What is the minimum spanning tree? Can a graph be drawn in a place with no crossing edges? Are two graphs “equivalent”? (isomorphism)

G RAPH S EARCH We learn about properties of a graph by systematically examining each of its vertices and edges, for example to compute the degree of all vertices, we visit each vertex and count it’s edges for path related properties, we have to move from vertex to vertex, along the graphs edges We implement a general graph search algorithms we can use to solve a wide range of graph problems

S IMPLE P ATH S EARCH Problem: is there a path from vertex v to vertex w ? Approach to solving problem: examine vertices adjacent to v if any of them is w, then we are done otherwise check if there is a path from any of the adjacent vertices repeat looking further and further from v Two different approaches to order of searching: breadth-first search (BFS), depth-first search (DFS)

BFS VS DFS PATH FINDING Is there a path from a to h?

DFS VS BFS A PPROACHES DFS and BFS are closely related. Implementation differs only their use of a stack or a queue BFS implemented via a queue of to-be-visited vertices DFS implemented via a stack of to-be-visited vertices (or recursion) Both approaches ignore some edges and avoid cycles by remembering previously visited vertices.

E XERCISE : DFS AND BFS T RAVERSAL Show the DFS order we visit to determine isPath(a,k) Show the BFS order we visit to determine isPath(a,k) Assume neighbours are chosen in alphabetical order

D EPTH F IRST S EARCH Basic approach to depth-first search: visit and mark current vertex for each neighbour, traverse it recursively Notes: need a mechanism for "marking" vertices in fact, we number them as we visit them (so that we could later trace path through graph) Make use of three global variables: count... counter to remember how many vertices traversed so far pre[]... array saying order in which each vertex was visited (pre stands for preorder) st[] … array storing the predecessor of each vertex (st stands for spanning tree)

9 D EPTH F IRST S EARCH T REE The edges traversed in a graph walk form a tree It corresponds to the call tree of the recursive dfs function Represents the original graph minus any cycles or alternate paths We can use a tree to encode the whole search process Each time we visit a vertex we record the previous vertex we came from - if the graph is connected this forms a spanning tree We store this in the st array

D EPTH F IRST S EARCH (DFS) // Assume we start with dummy Edge {0,0} // assume we start with count = 0 // pre[v] = -1 for all v // st[v] = -1 for all v (stores the predecessor) // assume adjacency matrix representation void dfsR (Graph g, Edge e) { Vertex i, w = e.w; pre[w] = count++; st[w] = e.v; for (i=0; i V; i++){ if ((g->edges[w][i] == 1) && (pre[i] == -1) dfsR (g, mkEdge(g,w,i)); } // Assume we start with dummy Edge {0,0} // assume we start with count = 0 // pre[v] = -1 for all v // st[v] = -1 for all v (stores the predecessor) // assume adjacency matrix representation void dfsR (Graph g, Edge e) { Vertex i, w = e.w; pre[w] = count++; st[w] = e.v; for (i=0; i V; i++){ if ((g->edges[w][i] == 1) && (pre[i] == -1) dfsR (g, mkEdge(g,w,i)); }

D EPTH F IRST S EARCH (DFS) the edges traversed in the graph walk form a tree the tree corresponds to the call tree of the depth first search and to the contents of the st array - spanning tree pre contains the pre-ordering of the vertices pre st

P ROPERTIES OF DFS FORESTS If a graph is not connected it will produce a spanning forest If it is connected it will form a spanning tree we call an edge connecting a vertex with an ancestor in the DFS tree that is not its parent a back edge back edge

E XERCISE : DFS T RAVERSAL Which vertices will be visited during dfs(g) : How can we ensure that all vertices are visited?

G RAPH S EARCH FUNCTION The graph may not be connected We need to make sure that we visit every connected component: void dfSearch (Graph g) { int v; count = 0; pre = malloc (sizeof (int) * g->nV)); st = malloc(sizeof (int) * g->nV)); for (v = 0; v nV; v++){ pre[v] = -1; st[v] = -1; } for (v = 0; v V; v++) { if (pre[v] == -1) dfsR (g, mkEdge(g,v,v)); } void dfSearch (Graph g) { int v; count = 0; pre = malloc (sizeof (int) * g->nV)); st = malloc(sizeof (int) * g->nV)); for (v = 0; v nV; v++){ pre[v] = -1; st[v] = -1; } for (v = 0; v V; v++) { if (pre[v] == -1) dfsR (g, mkEdge(g,v,v)); } The work complexity of the graph search algorithm is O( V 2 ) for adjacency matrix representation, and O( V+E ) for adjacency list representation

E XERCISE : DFS T RAVERSAL Trace the execution of dfs(g,0) on: What if we were using DFS to search for a path from 0..5? We would get If we want the shortest (least edges/vertices) path we need to use BFS instead.

E XERCISE : DFS T RAVERSAL Show the final state of the pre and st arrays after dfs(g,0) :

N ON -R ECURSIVE D EPTH F IRST S EARCH We can use a stack instead of recursion: void dfs (Graph g, Edge e) { int i; Stack s = newStack(); StackPush (s,e); while (!StackIsEmpty(s)) { e = StackPop(s); if (pre[e.w] == -1) { pre[e.w] = count++; st[e.w] = e.v; for (i = 0; i nV; i++) { if ((g->edges[e.w][i] == 1)&& (pre[i] == -1)) { StackPush (s,mkEdge(g,e.w,i)); } void dfs (Graph g, Edge e) { int i; Stack s = newStack(); StackPush (s,e); while (!StackIsEmpty(s)) { e = StackPop(s); if (pre[e.w] == -1) { pre[e.w] = count++; st[e.w] = e.v; for (i = 0; i nV; i++) { if ((g->edges[e.w][i] == 1)&& (pre[i] == -1)) { StackPush (s,mkEdge(g,e.w,i)); }

DFS A LGORITHMS : C YCLE D ETECTION Cycle detection: does a given graph have any cycles? if and only if the DFS graph has back edges, it contains cycles we can easily detect this in the DFS search:

DFS A LGORITHMS : C YCLE D ETECTION We are only checking for the existence of cycle, we are not returning it //Return 1 if there is a cycle int hasCycle (Graph g, Edge e) { int i, w = e.w; pre[w] = count++; st[w] = e.v; for (i=0; i V; i++){ if ((g->edges[w][i] == 1) && (pre[i] == -1)) { if(hasCycle (g, mkEdge(g,w,i))) return 1; } else if( (g->edges[w][i] == 1) && i != e.v){ //if it is not the predecessor return 1; } return 0; } //Return 1 if there is a cycle int hasCycle (Graph g, Edge e) { int i, w = e.w; pre[w] = count++; st[w] = e.v; for (i=0; i V; i++){ if ((g->edges[w][i] == 1) && (pre[i] == -1)) { if(hasCycle (g, mkEdge(g,w,i))) return 1; } else if( (g->edges[w][i] == 1) && i != e.v){ //if it is not the predecessor return 1; } return 0; }

DFS A LGORITHMS : C ONNECTIVITY Each vertex belongs to a connected component The function connectedComponents sets up the array cc to indicate which component contains each vertex cc

void connectedR (Graph g, Edge e) { int i, w = e.w; pre[w] = count++; st[w] = e.v; cc[w] = ccCount; for (i=0; i V; i++){ if ((g->edges[currV][i] == 1) && (pre[i] == -1)) { dfsR (g, mkEdge(g,w,i)); } void connectedR (Graph g, Edge e) { int i, w = e.w; pre[w] = count++; st[w] = e.v; cc[w] = ccCount; for (i=0; i V; i++){ if ((g->edges[currV][i] == 1) && (pre[i] == -1)) { dfsR (g, mkEdge(g,w,i)); } DFS A LGORITHMS Connectivity: maintain an extra array cc for connected components void connectedComponents (Graph g) { int v; count = 0; ccCount = 0; pre = malloc (g->nV *sizeof (int)); cc = malloc (g->nV *sizeof (int)); st = malloc (g->nV *sizeof (int)); for (v = 0; v nV; v++) { pre[v] = -1; st[v] = -1; cc[v] = -1; } for (v = 0; v V; v++) { if (pre[v] == -1) { connectedR (g, mkEdge(g,v,v)); ccCount++; } void connectedComponents (Graph g) { int v; count = 0; ccCount = 0; pre = malloc (g->nV *sizeof (int)); cc = malloc (g->nV *sizeof (int)); st = malloc (g->nV *sizeof (int)); for (v = 0; v nV; v++) { pre[v] = -1; st[v] = -1; cc[v] = -1; } for (v = 0; v V; v++) { if (pre[v] == -1) { connectedR (g, mkEdge(g,v,v)); ccCount++; }

B READTH -F IRST S EARCH What if we want the shortest path between two vertices? DFS doesn’t help us with this problem To find the shortest path between v and any vertex w we visit all the vertices adjacent to v (distance 1) then all the vertices adjacent to those we visited in the first step (distance 2)

B READTH -F IRST S EARCH We observed previously that we can simply replace the stack with a queue in the non- recursive implementation to get breadth -first search: void bfs (Graph g, Edge e) { int i; Queue q = newQueue(); QueueJoin(q,e); while (!QueueIsEmpty(q)) { e = QueueLeave(q); if(pre[e.w] == -1){ pre[e.w] = count++; st[e.w] = e.v; for (i = 0; i nV; i++){ if ((g->edges[e.w][i] != 0)&& (pre[i] == -1)) { QueueJoin (q,mkEdge(g,e.w,i)); } void bfs (Graph g, Edge e) { int i; Queue q = newQueue(); QueueJoin(q,e); while (!QueueIsEmpty(q)) { e = QueueLeave(q); if(pre[e.w] == -1){ pre[e.w] = count++; st[e.w] = e.v; for (i = 0; i nV; i++){ if ((g->edges[e.w][i] != 0)&& (pre[i] == -1)) { QueueJoin (q,mkEdge(g,e.w,i)); }

I MPROVED B READTH -F IRST S EARCH We can mark them as visited as we put them on the queue since the queue will retain their order. Queue will have at most V entries void bfs (Graph g, Edge e) { int i; Queue q = newQueue(); QueueJoin (q,e); pre[e.w] = count++; st[e.w] = e.v; while (!QueueIsEmpty(q)) { e = QueueLeave(q); for (i = 0; i V; i++) { if ((g->edges[e.w][i] != 0)&&(pre[i] == -1)) { QueueJoin (q,mkEdge(g,e.w,i)); pre[i] = count++; st[i] = e.w; } void bfs (Graph g, Edge e) { int i; Queue q = newQueue(); QueueJoin (q,e); pre[e.w] = count++; st[e.w] = e.v; while (!QueueIsEmpty(q)) { e = QueueLeave(q); for (i = 0; i V; i++) { if ((g->edges[e.w][i] != 0)&&(pre[i] == -1)) { QueueJoin (q,mkEdge(g,e.w,i)); pre[i] = count++; st[i] = e.w; }

E XERCISE : BFS T RAVERSAL Show the final state of the pre and st arrays after bfs(g,0) : Write code to print out the shortest path from 0 to a given vertex v using the st array.

B READTH -F IRST S EARCH For one BFS: O(V^2) for adjacency matrix and O(V+E) for adjacency list We can do BFS for every node as root node, and store the resulting spanning trees in a V x V matrix to store all the shortest paths between any two vertices To store and calculate these spanning trees, we need memory proportional to V * V time proportional to V * E Then, we can return path length in constant time path in time proportional to the path length