Using nextAdjacent() To list all vertices connected to a vertex u in graph G we can use the following loop: for (int v=G.nextAdjacent(u,-1); v>=0; v=G.nextAdjacent(u,v))

Slides:



Advertisements
Similar presentations
CSE 390B: Graph Algorithms Based on CSE 373 slides by Jessica Miller, Ruth Anderson 1.
Advertisements

Graphs CSC 220 Data Structure. Introduction One of the Most versatile data structures like trees. Terminology –Nodes in trees are vertices in graphs.
CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
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
© 2006 Pearson Addison-Wesley. All rights reserved14 A-1 Chapter 14 excerpts Graphs (breadth-first-search)
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Data Structure and Algorithms (BCS 1223) GRAPH. Introduction of Graph A graph G consists of two things: 1.A set V of elements called nodes(or points or.
Graphs CS3240, L. grewe.
Graph.
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
Graphs. John Edgar  Understand graph terminology  Implement graphs using  Adjacency lists and  Adjacency matrices  Perform graph searches  Depth.
Graph & BFS.
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.
Hashing with Separate Chaining Implementation – data members public class SCHashTable implements HashTableInterface { private List [] table; private int.
Graph & BFS Lecture 22 COMP171 Fall Graph & BFS / Slide 2 Graphs * Extremely useful tool in modeling problems * Consist of: n Vertices n Edges D.
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
CS 206 Introduction to Computer Science II 11 / 03 / 2008 Instructor: Michael Eckmann.
Graphs. Graphs Many interesting situations can be modeled by a graph. Many interesting situations can be modeled by a graph. Ex. Mass transportation system,
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
© 2006 Pearson Addison-Wesley. All rights reserved14 B-1 Chapter 14 (continued) Graphs.
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.
Graphs & Graph Algorithms Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Shortest Path Problem For weighted graphs it is often useful to find the shortest path between two vertices Here, the “shortest path” is the path that.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
Computer Science 112 Fundamentals of Programming II Graph Algorithms.
Search Related Algorithms. Graph Code Adjacency List Representation:
© 2006 Pearson Addison-Wesley. All rights reserved14 A-1 Chapter 14 Graphs.
Chapter 14 Graphs. © 2004 Pearson Addison-Wesley. All rights reserved Terminology G = {V, E} A graph G consists of two sets –A set V of vertices,
CS200 Algorithms and Data StructuresColorado State University Part 10. Graphs CS 200 Algorithms and Data Structures 1.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Common final examinations When: Wednesday, 12/11, 3:30-5:30 PM Where: Ritter Hall - Walk Auditorium 131 CIS 1166 final When: Wednesday, 12/11, 5:45-7:45.
Graphs. Made up of vertices and arcs Digraph (directed graph) –All arcs have arrows that give direction –You can only traverse the graph in the direction.
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.
COMP261 Lecture 6 Dijkstra’s Algorithm. Connectedness Is this graph connected or not? A Z FF C M N B Y BB S P DDGG AA R F G J L EE CC Q O V D T H W E.
Graph Introduction, Searching Graph Theory Basics - Anil Kishore.
Graphs A graphs is an abstract representation of a set of objects, called vertices or nodes, where some pairs of the objects are connected by links, called.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
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.
Graphs Slide credits:  K. Wayne, Princeton U.  C. E. Leiserson and E. Demaine, MIT  K. Birman, Cornell U.
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
7. Graph Traversal Describe and compare depth-first and breadth-first graph searching, and look at the creation of spanning trees Contest Algorithms: 7.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 7: Graphs Data Structures.
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)
Graph Theory Def: A graph is a set of vertices and edges G={V,E} Ex. V = {a,b,c,d,e} E = {ab,bd,ad,ed,ce,cd} Note: above is a purely mathematical definition.
Lecture #13. Topics 1.The Graph Abstract Data Type. 2.Graph Representations. 3.Elementary Graph Operations.
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,
Graphs Chapter 15 introduces graphs which are probably the most general and commonly-used data structure. This lecture introduces heaps, which are used.
CS212: Data Structures and Algorithms
Graphs Representation, BFS, DFS
Csc 2720 Instructor: Zhuojun Duan
CS202 - Fundamental Structures of Computer Science II
Data Structures and Algorithms for Information Processing
Graphs Representation, BFS, DFS
Chapter 11 Graphs.
Graphs – Adjacency Matrix
Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Spanning Trees Longin Jan Latecki Temple University based on slides by
Chapter 14 Graphs © 2006 Pearson Addison-Wesley. All rights reserved.
Graph Implementation.
Chapter 14 Graphs © 2011 Pearson Addison-Wesley. All rights reserved.
GRAPH – Definitions A graph G = (V, E) consists of
Presentation transcript:

Using nextAdjacent() To list all vertices connected to a vertex u in graph G we can use the following loop: for (int v=G.nextAdjacent(u,-1); v>=0; v=G.nextAdjacent(u,v)) { System.out.print(v); }

Adjacency Lists The edges are recorded in an array of size  V  of linked lists In an unweighted graph a list at index i records the keys of the vertices adjacent to vertex i In a weighted graph a list at index i contains pairs which record vertex keys (of vertices adjacent to i) and their associated edge weights Looking up an edge requires time proportional to the number of edges adjacent to a node (a degree of a vertex) Finding all vertices adjacent to a given vertex also takes time proportional to the degree of the vertex (which is minimal possible) The list requires O (  E  ) space

Adjacency List Examples A B C D E F G BAC DE GF A B C D E F G BAC DE GF B1BCDFACEGABEGABCGAGBCEF3D5F2E5A2B4C1A2C3G8G

Implementation with adjacency lists class Graph { // simple graph (no multiple edges); undirected; unweighted private int numVertices; private int numEdges; private List adjList[]; public Graph(int n) { numVertices = n; numEdges = 0; adjList = new List[n]; for (int i=0; i<n; i++) adjList[i] = new List (); } // end constructor public int getNumVertices() { return numVertices; } public int getNumEdges() { return numEdges; } public boolean isEdge(int v, int w) { List L = adjList[v]; for (int i=1; i<=L.size(); i++) if (L.get(i).intValue() == w) return true; return false; } // end getWeight

public void addEdge(int v, int w) { if (!isEdge(v,w)) { adjList[v].add(adjList[v].size()+1,new Integer(w)); adjList[w].add(adjList[w].size()+1,new Integer(v)); numEdges++; } } // end addEdge public void removeEdge(int v, int w) { for (int i=1; i<=adjList[v].size(); i++) if (adjList[v].get(i).intValue() == w) { adjList[v].remove(i); break; } for (int i=1; i<=adjList[w].size(); i++) if (adjList[w].get(i).intValue() == v) { adjList[w].remove(i); numEdges--; break; } } // end remove

public int kth_Adjacent(int v,int k) // return the k-th adjacent vertex to v // or -1 if degree of v is smaller than k { List L = adjList[v]; if (k>=1 && k<=L.size()) return L.get(k).intValue(); else return -1; } } // end Graph

Using kth_Adjacent() To list all vertices connected to a vertex u in graph G we can use the following loop: int v; for (int k=1; (v=G.kth_Adjacent(u,k)) >=0; k++) System.out.print(v);

nextAdjacent() and kth_Adjacent() Why do we have different methods to access neighbors of a vertex in different implementations? we could implement nextAdjacent() in the list implementation and kth_Adjacent() in the matrix implementation of graphs, but they would not be efficient to have a common way how to list the neighbors in both implementations, we would have to use “iterators” (see section 9.5 in the textbook – not covered for this course)

Graph Traversals A graph traversal algorithm visits all of the vertices that it can reach If the graph is not connected all of the vertices will not be visited Therefore a graph traversal algorithm can be used to see if a graph is connected (or count the number of connected parts (= components)) Vertices should be marked as “visited” Otherwise, a traversal will go into an infinite loop if the graph contains a cycle

Breadth First Search After visiting a vertex, v, visit every vertex adjacent to v before moving on Use a queue to store nodes whose neighbors we still need to visit BFS: visit and insert start while (q not empty) remove node from q and make it current visit and insert the unvisited nodes adjacent to current start

Breadth First Search Example BDEA G C K F HIJ A B F G C H I J D K E queuevisited A B F G C H I J D K E

BFS - Remarks BFS is visiting nodes which are close to the start vertex first, then more distant nodes, etc. what distance is it? a graph distance of two vertices u and v is the number of edges on (length of) the shortest path connecting u and v in weighted graph, the sum of weights of edges of a path is called weight or cost of the path.

BFS Algorithm public static void BreadthFirstSearch(GraphList G, int start) { int n = G.getNumVertices(); // create an array where we mark visited vertices boolean[] visited = new boolean[n]; // initialized to false // create a queue Queue q = new Queue (); q.enqueue(new Integer(start)); visit(start); visited[start] = true; while (!q.isEmpty()) { Integer current = q.dequeue(); int v; for (int k=1; (v=G.kth_Adjacent(current.intValue(),k)) >=0; k++) if (!visited[v]) { q.enqueue(new Integer(v)); visit(v); visited[v] = true; }

Depth First Search Visit a vertex, v, move from v as deeply as possible Use a stack s to store nodes DFS: visit and push start while (s not empty) peek at node, nd, at top of s if nd has an unvisited neighbour visit it and push it onto s else pop nd from s start

Depth First Search Example BDEA G C K F HIJ A J I G H F E D C B K stackvisited A B C D E F G H I J K Invariant: the sequence of vertices on the stack forms a simple path in the graph starting in the vertex start.

DFS Algorithm public static void DepthFirstSearch(GraphMatrix G, int start) { int n = G.getNumVertices(); // create an array where we mark visited vertices boolean[] visited = new boolean[n]; // initialized to false // create a queue Stack s = new Stack (); s.push(new Integer(start)); visit(start); visited[start] = true; while (!s.isEmpty()) { int u = s.peek().intValue(); // the vertex at the top of stack boolean hasUnvisitedNeighbor = false; for (int v=G.nextAdjacent(u,-1); v>=0; v=G.nextAdjacent(u,v)) if (!visited[v]) { s.push(new Integer(v)); visit(v); visited[v] = true; hasUnvisitedNeighbor = true; break; } if (!hasUnvisitedNeighbor) s.pop(); }

DFS - Remarks what Depth First Search does is backtracking (which is also indicated since we are using stack) one could easily write a recursive version of DFS