Graphs – Part II CS 367 – Introduction to Data Structures.

Slides:



Advertisements
Similar presentations
CS203 Lecture 15.
Advertisements

Graphs COP Graphs  Train Lines Gainesville OcalaDeltona Daytona Melbourne Lakeland Tampa Orlando.
CSE 390B: Graph Algorithms Based on CSE 373 slides by Jessica Miller, Ruth Anderson 1.
Recursion CS 367 – Introduction to Data Structures.
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.
Chapter 8, Part I Graph Algorithms.
1 Graphs: Traversal Searching/Traversing a graph = visiting the vertices of a graph by following the edges in a systematic way Example: Given a highway.
CS 206 Introduction to Computer Science II 11 / 07 / 2008 Instructor: Michael Eckmann.
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.
Graphs By JJ Shepherd. Introduction Graphs are simply trees with looser restrictions – You can have cycles Historically hard to deal with in computers.
Advanced Data Structures
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
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,
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Graph Traversals Depth-First Traversals. –Algorithms. –Example. –Implementation. Breadth-First Traversal. –The Algorithm. –Example. –Implementation. Review.
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.
Alyce Brady CS 510: Computer Algorithms Depth-First Graph Traversal Algorithm.
Graph Traversals General Traversal Algorithm Depth-First Traversals. –Algorithms. –Example. –Implementation. Breadth-First Traversal. –The Algorithm. –Example.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 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.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
Trees, Binary Search Trees, Recursion, Project 2 Bryce Boe 2013/08/01 CS24, Summer 2013 C.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Trees – Part 2 CS 367 – Introduction to Data Structures.
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.
CS 206 Introduction to Computer Science II 11 / 16 / 2009 Instructor: Michael Eckmann.
Where’s the title? You gotta search for it!. PotW Solution String s = new Scanner(System.in).next(); int[] prev = new int[s.length() * 2 + 2]; Arrays.fill(prev,
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
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
Graphs and Paths : Chapter 15 Saurav Karmakar
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 7: Graphs Data Structures.
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
CS 367 Introduction to Data Structures Lecture 13.
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.
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.
Graph Representations adjacency matrix node list edge list ADF CH BEG A B C D E F G H A B C D
Graphs – Part III CS 367 – Introduction to Data Structures.
Breadth-First Search (BFS)
Graphs A New Data Structure
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
Graph Representations
Csc 2720 Instructor: Zhuojun Duan
Cse 373 May 8th – Dijkstras.
Cse 373 April 14th – TreEs pt 2.
Data Structures and Algorithms for Information Processing
Graph Traversals Depth-First Traversals. Algorithms. Example.
Graphs Representation, BFS, DFS
Lesson Objectives Aims
Graphs Chapter 13.
Chapter 11 Graphs.
Graph Traversals Depth-First Traversals. Algorithms. Example.
Graphs Part 2 Adjacency Matrix
CMSC 202 Trees.
COMP171 Depth-First Search.
Depth-First Search CSE 2011 Winter April 2019.
Depth-First Search CSE 2011 Winter April 2019.
Graphs.
Applications of BFS CSE 2011 Winter /17/2019 7:03 AM.
Graph Traversals Depth-First Traversals. Algorithms. Example.
INTRODUCTION A graph G=(V,E) consists of a finite non empty set of vertices V , and a finite set of edges E which connect pairs of vertices .
Presentation transcript:

Graphs – Part II CS 367 – Introduction to Data Structures

Implementing a Graph Nodes –must store data Graph –must have an adjacency list (or matrix) we will use an adjacency matrix –for best performance, should have access to all nodes in the graph we will keep an array of references to each node there are other ways to do this Many ways to implement a graph – we will look at just one possible implementation

Cycles A cycle is defined as a route from: N 0 to N 1 to … N m-1 to N m where N 0 equals N m In other words, you follow some path of edges that leads you back to the node you started at A B D C E F Cycle A -> B -> D -> A

Cycles If cycles are not considered, it is easy to end up with code that results in an infinite loop –to prevent this, mark each visited node with a special flag –before starting a search, mark the node as false –after visiting a node, mark it as true –do not go to nodes that are already marked as visited

Graph Methods Many possible methods to put in a graph class –insert, remove, search, etc. For now, we will only consider searching a graph for data –assume we have a method to build the graph based on a data file we’ll show how to do this later

Graph Searching Unlike a tree, a graph is not required to have a specific ordering of data –in fact, in many graphs this would be impossible –must traverse the entire graph to find the data Two possible graph traversal methods –depth first search –breadth first search To simplify things, we will assume that the search methods do the following –accept an object that indicates where the search should start –goes through every node in the graph and prints out

Graph Node Class class GraphNode { public Object data; public boolean visited; public int index; public GraphNode(Object data) { this.data = data; visited = false; } There may be much more data than this stored in a node –this will be fine for our examples

Graph Class class Graph { private GraphNode[ ] nodes; private int[ ][ ] matrix; public Graph(int numNodes, String dataFile) { nodes = new GraphNode[numNodes]; matrix = new int[numNodes][numNodes]; createGraph(nodes, matrix, dataFile); } private void createGraph(GraphNode[ ] nodes, int[ ][ ] matrix, String data); public void depthFirst(Object start) { for(int i=0; i<nodes.lenth; i++) { nodes[i].visited = false; } for(int i=0; i<nodes.length; i++) if(nodes[i].data.equals(start)) { depthFirst(i); return; } System.out.println(“Starting point not in graph.”); } private void depthFirst(int start); public void breadthFirst(Object start) { … } private void breadthFirst(int start); }

Depth First Search The idea of depth in a graph is how far from the source node can you go –visit a node, N –visit the first neighbor, N 1, of N –visit N 1 ’s first neighbor, N 11, and so on be careful not to visit an already visited node once the first adjacent node has been visited (and each of its adjacent nodes), move to the next node –repeat this until all the nodes are visited

Depth First Search Implementation –two possible implementations recursion stack –both methods are similar push a node on the stack (user or program stack) visit the node look at the nodes adjacency list (or matrix) select the first unvisited adjacent node visit that node and repeat the process

Depth First Search - Recursion // notice that no error checking is being performed – there should be! public void depthFirst(int start) { GraphNode cur = nodes[start]; cur.visited = true; System.out.println(cur.data); for(int i=0; i<nodes.length; i++) { if((matrix[start][i] == 1) && (nodes[i].visited == false)) depthFirst(i); } Again, in reality more than simply printing a nodes value would occur on a visit to the node

Depth First Search - Recursion A B D C E F depthFirst(A) AA B A B F A B F E A B F A B A B D A B AA C A Program Stack

Depth First Search It should be clear from the previous example that using recursion to do a depth first search involves using a stack –the program stack in this case –implicitly handled by the compiler You should also be able to convert this into a program that uses and explicit stack –similar to your flight path program that first used recursion and then a stack

Breadth First Search The idea of breadth in a graph deals with visiting all of a nodes neighbors before moving on –visit a node, N –visit all of N’s neighbors –then go to N’s first neighbor, N 1, and visit all of N 1 ’s neighbors –then to to N’s next neighbor, N 2, and visit all of N 2 ’s neighbors –repeat this until all the nodes are visited

Breadth First Search Implementation –use a queue to store each visited node’s neighbors –start by enqueueing the root –dequeue the first node from the queue visit the node –enqueue all of the nodes neighbors be careful not to enqueue an already visited node –dequeue the next node from the queue and repeat the process

Breadth First Search // notice that no error checking is being performed – there should be! public void breadthFirst(int start) { QueueList queue = new QueueList(); queue.enqueue(nodes[start]); while(!queue.isEmpty()) { GraphNode tmp = (GraphNode)queue.dequeue(); System.out.println(tmp.data); for(int i=0; i<nodes.length; i++) { if((matrix[tmp.index][i] == 1) && (nodes[i].visited == false)) queue.enqueue(nodes[i]); }

Breadth First Search A B D C E F breadthFirst(A) A BC CDF DF F E visit A visit B visit C visit D visit F visit E

Creating the Graph The constructor for a graph contained createGraph(nodes, matrix, dataFile); How is the graph originally constructed? –it depends on the format of the initial data –in this case, we assume a file contains all the information it could be gotten through user input the graph could be built as needed –consider a chess game again – build the nodes as needed

Creating a Graph from a File Assume a data file where the first column represents a node –every other column on a line represent immediate neighbors to the first node Data File A B C B D F C D D A F E A B D C E F

Creating a Graph from a File Basic concept –initialize the matrix array to all zeroes –read a line from the file –create a new GraphNode for each column that has not yet been created insert it into the nodes array –go to the row in the matrix indicated by the first column –go through the row and place a one for every neighbor listed in the file

private void createGraph(GraphNode[ ] nodes, int[ ][ ] matrix, String file) { // open the file for reading // initialize matrix array to all zeroes // read the first line from the file while(line != null) { StringTokenizer tok = new StringTokenizer(line); // if the first token isn’t in the nodes array, add it // set row equal to the location of the first token in the nodes array while(tok.hasMoreTokens()) { String tmp = tok.next(); // if tmp isn’t in nodes array, add it and place a 1 in matrix // otherwise, just place a 1 in matrix } // read the next line from the file } Creating a Graph from a File

Creating a graph from a File One caution when creating the graph –need to make sure that nodes array indices are aligned with matrix indices –in other words, if node B is found at index 1 of the nodes array, it should also be represented by row 1 and column 1 in the matrix array