DataStruct 13. Graph Algorithms

Size: px
Start display at page:

Download "DataStruct 13. Graph Algorithms"

Transcription

1 DataStruct 13. Graph Algorithms Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., December 10, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, College of Engineering, Yeungnam University, KOREA (Tel : ; Fax : ytkim@yu.ac.kr)

2 Graphs Data Structures for Graphs Graph Traversals Directed Graphs Shortest Paths Minimum Spanning Trees Outline DS 13-2

3 13.1 Graphs Graphs Definition Applications Terminology Properties ADT SFO ORD LAX DFW DS 13-3

4 Graph A graph is a pair (V, E), where V is a set of nodes, called vertices E is a collection of pairs of vertices, called edges Vertices and edges are positions and store elements Example: A vertex represents an airport and stores the three-letter airport code An edge represents a flight route between two airports and stores the mileage of the route SFO ORD LGA PVD HNL LAX DFW MIA DS 13-4

5 Edge Types Directed edge ordered pair of vertices (u,v) first vertex u is the origin second vertex v is the destination e.g., a flight Undirected edge unordered pair of vertices (u,v) e.g., a flight route Directed graph all the edges are directed e.g., route network Undirected graph all the edges are undirected e.g., flight network ORD ORD 849 miles flight AA 1206 PVD PVD DS 13-5

6 Applications Graphs Electronic circuits Printed circuit board Integrated circuit Transportation networks Highway network Flight network Computer networks Local area network Internet Web Databases Entity-relationship diagram cslab1a cslab1b math.brown.edu cs.brown.edu brown.edu qwest.net att.net cox.net John Paul David DS 13-6

7 Terminology Graphs End vertices (or endpoints) of an edge U and V are the endpoints of a Edges incident on a vertex a, d, and b are incident on V Adjacent vertices U and V are adjacent Degree of a vertex X has degree 5 Parallel edges h and i are parallel edges Self-loop j is a self-loop U a c V W d f b e X Y g h i Z j DS 13-7

8 Terminology (cont.) Graphs Path sequence of alternating vertices and edges begins with a vertex ends with a vertex each edge is preceded and followed by its endpoints Simple path path such that all its vertices and edges are distinct Examples P 1 =(V,b,X,h,Z) is a simple path P 2 =(U,c,W,e,X,g,Y,f,W,d,V) is a path that is not simple U a c d P 2 V W f e b P 1 X g Y h Z DS 13-8

9 Terminology (cont.) Graphs Cycle circular sequence of alternating vertices and edges a V b each edge is preceded and followed by its endpoints Simple cycle cycle such that all its vertices and edges are distinct U c d C 2 W e X g C 1 h Z Examples f C 1 =(V,b,X,g,Y,f,W,c,U,a, ) is a simple cycle Y C 2 =(U,c,W,e,X,g,Y,f,W,d,V,a, ) is a cycle that is not simple DS 13-9

10 Properties Graphs Property 1 v deg(v) = 2m Proof: each edge is counted twice Property 2 In an undirected graph with no self-loops and no multiple edges m n (n - 1)/2 Proof: each vertex has degree at most (n - 1) Notation - Example n m deg(v) n = 4 m = 6 deg(v) = 3 number of vertices number of edges degree of vertex v What is the bound for a directed graph? DS 13-10

11 Main Methods of the Graph ADT Graphs Vertices and edges are positions store elements Accessor methods avertex() incidentedges(v) endvertices(e) isdirected(e) origin(e) destination(e) opposite(v, e) areadjacent(v, w) Update methods insertvertex(o) insertedge(v, w, o) insertdirectededge(v, w, o) removevertex(v) removeedge(e) Generic methods numvertices() numedges() vertices() edges() DS 13-11

12 3.2 Data Structures for Graphs Data structures for graphs Edge list structure Adjacency list structure Adjacency matrix structure DS 13-12

13 Vertex object element reference to position in vertex sequence Edge object element origin vertex object destination vertex object reference to position in edge sequence Vertex sequence sequence of vertex objects Edge sequence sequence of edge objects Edge List Structure v a u b c u v w z a w d b c d z Graphs DS 13-13

14 Adjacency List Structure Graphs Edge list structure Incidence sequence for each vertex sequence of references to edge objects of incident edges Augmented edge objects references to associated positions in incidence sequences of end vertices a v b u w u v w a b DS 13-14

15 Adjacency Matrix Structure Edge list structure Augmented vertex objects Integer key (index) associated with vertex 2D-array adjacency array Reference to edge object for adjacent vertices Null for non nonadjacent vertices The old fashioned version just has 0 for no edge and 1 for edge u a 0 u 1 v 2 w a v b w Graphs b DS 13-15

16 Asymptotic Performance n vertices, m edges no parallel edges no self-loops Bounds are big-oh Edge List Adjacency List Adjacency Matrix Space n + m n + m n 2 incidentedges(v) m deg(v) n areadjacent (v, w) m min(deg(v), deg(w)) 1 insertvertex(o) 1 1 n 2 insertedge(v, w, o) removevertex(v) m deg(v) n 2 removeedge(e) DS 13-16

17 13.3 Graph Traversals Definitions Subgraph Connectivity Spanning trees and forests Depth-first search Algorithm Example A Properties Analysis B D E Applications of DFS Path finding C Cycle finding DS 13-17

18 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 of G A spanning subgraph of G is a subgraph that contains all the vertices of G Subgraph Depth-First Search Spanning subgraph DS 13-18

19 Connectivity A graph is connected if there is a path between every pair of vertices A connected component of a graph G is a maximal connected subgraph of G Connected graph Depth-First Search Non connected graph with two connected components DS 13-19

20 Trees and Forests A (free) tree is an undirected graph T such that T is connected T has no cycles This definition of tree is different from the one of a rooted tree A forest is an undirected graph without cycles The connected components of a forest are trees Tree Depth-First Search Forest DS 13-20

21 Spanning Trees and Forests A spanning tree of a connected graph is a spanning subgraph that is a tree A spanning tree is not unique unless the graph is a tree Spanning trees have applications to the design of communication networks A spanning forest of a graph is a spanning subgraph that is a forest Graph Spanning tree Depth-First Search DS 13-21

22 Depth-First Search (DFS) Depth-first search (DFS) is a general technique for traversing a graph A DFS traversal of a graph G Visits all the vertices and edges of G Determines whether G is connected Computes the connected components of G Computes a spanning forest of G DFS on a graph with n vertices and m edges takes O(n + m ) time DFS can be further extended to solve other graph problems Find and report a path between two given vertices Find a cycle in the graph Depth-first search is to graphs what Euler tour is to binary trees DS 13-22

23 DFS Algorithm The algorithm uses a mechanism for setting and getting labels of vertices and edges Algorithm DFS(G) Input graph G Output labeling of the edges of G as discovery edges and back edges for all u G.vertices() setlabel(u, UNEXPLORED) for all e G.edges() setlabel(e, UNEXPLORED) for all v G.vertices() if getlabel(v) = UNEXPLORED DFS(G, v) Algorithm DFS(G, v) Input graph G and a start vertex v of G Output labeling of the edges of G in the connected component of v as discovery edges and back edges setlabel(v, VISITED) for all e G.incidentEdges(v) if getlabel(e) = UNEXPLORED w opposite(v,e) if getlabel(w) = UNEXPLORED setlabel(e, DISCOVERY) DFS(G, w) else setlabel(e, BACK) DS 13-23

24 Example A unexplored vertex A A visited vertex unexplored edge B D E discovery edge back edge C A A B D E B D E C C DS 13-24

25 Example (cont.) A A B D E B D E C C A A B D E B D E C C DS 13-25

26 DFS and Maze Traversal The DFS algorithm is similar to a classic strategy for exploring a maze We mark each intersection, corner and dead end (vertex) visited We mark each corridor (edge ) traversed We keep track of the path back to the entrance (start vertex) by means of a rope (recursion stack) DS 13-26

27 Property 1 DFS(G, v) visits all the vertices and edges in the connected component of v Property 2 The discovery edges labeled by DFS(G, v) form a spanning tree of the connected component of v Properties of DFS B A C D E DS 13-27

28 Analysis of DFS Setting/getting a vertex/edge label takes O(1) time Each vertex is labeled twice once as UNEXPLORED once as VISITED Each edge is labeled twice once as UNEXPLORED once as DISCOVERY or BACK Method incidentedges is called once for each vertex DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure Recall that S v deg(v) = 2m DS 13-28

29 Path Finding We can specialize the DFS algorithm to find a path between two given vertices v and z using the template method pattern We call DFS(G, v,z) with v as the start vertex We use a stack S to keep track of the path between the start vertex and the current vertex As soon as destination vertex z is encountered, we return the path as the contents of the stack Algorithm pathdfs(g, v, z) setlabel(v, VISITED) S.push(v) if v = z return S.elements() for all e G.incidentEdges(v) if getlabel(e) = UNEXPLORED w opposite(v,e) if getlabel(w) = UNEXPLORED setlabel(e, DISCOVERY) S.push(e) pathdfs(g, w, z) S.pop(e) else setlabel(e, BACK) S.pop(v) DS 13-29

30 Cycle Finding We can specialize the DFS algorithm to find a simple cycle using the template method pattern We use a stack S to keep track of the path between the start vertex and the current vertex As soon as a back edge (v, w) is encountered, we return the cycle as the portion of the stack from the top to vertex w Algorithm cycledfs(g, v) setlabel(v, VISITED) S.push(v) for all e G.incidentEdges(v) if getlabel(e) = UNEXPLORED w opposite(v,e) S.push(e) if getlabel(w) = UNEXPLORED setlabel(e, DISCOVERY) if ((U=cycleDFS(G, w)=empty) S.pop(e) else return U else T new empty stack repeat o S.pop() T.push(o) until o = w return T.elements() S.pop(v) DS 13-30

31 Generic DFC Implementation in C++ Graph.h (1) /** Graph.h (1) */ #ifndef GRAPH_H #define GRAPH_H #include <list> #include <vector> #include <iostream> #include <iomanip> #include <limits> #include <string> #define PLUS_INF INT_MAX/2 enum VertexStatus UN_VISITED, VISITED, VRTX_NOT_FOUND; enum EdgeStatus DISCOVERY, BACK, CROSS, EDGE_UN_VISITED, EDGE_VISITED, EDGE_NOT_FOUND; using namespace std; class Graph // Graph based on Adjacency Matrix public: class Vertex; class Edge; DS 13-31

32 Graph.h (2) /** Graph.h (2) */ public: class Vertex friend ostream& operator<<(ostream& fout, Vertex v) fout << v.getname(); return fout; public: Vertex() : name(), ID(-1) Vertex(string n, int id, VertexStatus vs) : name(n), ID(id), vtxstatus(vs) Vertex(char *pn, int id, VertexStatus vs) : name(string(pn)), ID(id), vtxstatus(vs) Vertex(int id) : ID(id) string getname() return name; int getid() return ID; void setname(string c_name) name = c_name; void setid(int id) ID = id; bool operator==(vertex v) return ((ID == v.getid()) && (name == v.getname())); bool operator!=(vertex v) return ((ID!= v.getid()) (name!= v.getname())); void setvtxstatus(vertexstatus vs) vtxstatus = vs; VertexStatus getvtxstatus() return vtxstatus; DS 13-32

33 Graph.h (3) /** Graph.h (3) */ private: string name; int ID; VertexStatus vtxstatus; ; // end class Vertex public: typedef std::list<graph::vertex> VtxList; public: class Edge friend ostream& operator<<(ostream& fout, Edge& e) fout << "Edge(" << e.getvertex_1() << ", " << e.getvertex_2(); fout << ", d(" << setw(2) << e.getdistance() << "))"; return fout; public: Edge() : pvrtx_1(null), pvrtx_2(null), distance(plus_inf) Edge(Vertex v1, Vertex v2, int d) :vrtx_1(v1), vrtx_2(v2), distance(d), pvrtx_1(null), pvrtx_2(null), edgestatus(edge_un_visited DS 13-33

34 Graph.h (4) /** Graph.h (4) */ void endvertices(vtxlist& vtxlist) vtxlist.push_back(*pvrtx_1); vtxlist.push_back(*pvrtx_2); Vertex opposite(vertex v) if (v == *pvrtx_1) return *pvrtx_2; else if (v == *pvrtx_2) return *pvrtx_1; else //cout << "Error in opposite()" << endl; return Vertex(NULL); Vertex getvertex_1() return vrtx_1; Vertex getvertex_2() return vrtx_2; Vertex* getpvrtx_1() return pvrtx_1; Vertex* getpvrtx_2() return pvrtx_2; int getdistance() return distance; void setpvrtx_1(vertex* pv) pvrtx_1 = pv; void setpvrtx_2(vertex* pv) pvrtx_2 = pv; void setdistance(int d) distance = d; bool operator!=(edge e) return ((*pvrtx_1!= e.getvertex_1()) (*pvrtx_2!= e.getvertex_2())); bool operator==(edge e) return ((*pvrtx_1 == e.getvertex_1()) && (*pvrtx_2 == e.getvertex_2())); void setedgestatus(edgestatus es) edgestatus = es; EdgeStatus getedgestatus() return edgestatus; DS 13-34

35 Graph.h (5) /** Graph.h (5) */ private: Vertex vrtx_1; Vertex vrtx_2; Vertex* pvrtx_1; Vertex* pvrtx_2; int distance; EdgeStatus edgestatus; ; public: typedef std::list<graph::edge> EdgeList; public: typedef std::list<vertex> VtxList; typedef std::list<edge> EdgeList; typedef std::list<vertex>::iterator VtxItor; typedef std::list<edge>::iterator EdgeItor; Graph() : pvrtxarray(null), padjlstarray(null) // default constructor Graph(int num_nodes) : pvrtxarray(null), padjlstarray(null) typedef Edge* EdgePtr; num_vertices = num_nodes; pvrtxarray = new Graph::Vertex[num_vertices]; for (int i=0; i<num_nodes; i++) pvrtxarray[i] = NULL; DS 13-35

36 Graph.h (6) /** Graph.h (6) */ padjlstarray = new EdgeList[num_vertices]; for (int i=0; i<num_vertices; i++) padjlstarray[i].clear(); void vertices(vtxlist& vtxlst); void edges(edgelist&); bool isadjacentto(vertex v, Vertex w); void insertvertex(vertex& v); void insertedge(edge& e); void eraseedge(edge e); void erasevertex(vertex v); int getnumvertices() return num_vertices; void incidentedges(vertex v, EdgeList& edges); Vertex* getpvrtxarray() return pvrtxarray; EdgeList* getpadjlstarray() return padjlstarray; void printgraph(); private: Vertex* pvrtxarray; EdgeList* padjlstarray; int num_vertices; ; #endif DS 13-36

37 Graph.cpp (1) /** Graph.cpp (1) */ #include "Graph.h" using namespace std; typedef std::vector<graph::vertex> VtxList; typedef std::list<graph::edge> EdgeList; typedef std::vector<graph::vertex>::iterator VtxItor; typedef std::list<graph::edge>::iterator EdgeItor; void Graph::insertVertex(Vertex& v) int vtx_id; vtx_id = v.getid(); if (pvrtxarray[vtx_id] == NULL) pvrtxarray[vtx_id] = v; void Graph::vertices(VtxList& vtxlst) vtxlst.clear(); for (int i=0; i<getnumvertices(); i++) vtxlst.push_back(pvrtxarray[i]); DS 13-37

38 Graph.cpp (2) /** Graph.cpp (2) */ void Graph::insertEdge(Edge& e) Vertex vtx_1, vtx_2; Vertex* pvtx; int vtx_1_id, vtx_2_id; vtx_1 = e.getvertex_1(); vtx_2 = e.getvertex_2(); vtx_1_id = vtx_1.getid(); vtx_2_id = vtx_2.getid(); if (pvrtxarray[vtx_1_id] == NULL) pvrtxarray[vtx_1_id] = vtx_1; if (pvrtxarray[vtx_2_id] == NULL) pvrtxarray[vtx_2_id] = vtx_2; e.setpvrtx_1(&pvrtxarray[vtx_1_id]); e.setpvrtx_2(&pvrtxarray[vtx_2_id]); //edgelist.push_back(e); padjlstarray[vtx_1_id].push_back(e); DS 13-38

39 Graph.cpp (3) /** Graph.cpp (3) */ void Graph::edges(EdgeList& edges) EdgeItor eitor; edges.clear(); for (int i=0; i<getnumvertices(); i++) eitor = padjlstarray[i].begin(); while (eitor!= padjlstarray[i].end()) edges.push_back(*eitor); eitor++; DS 13-39

40 Graph.cpp (4) /** Graph.cpp (4) */ void Graph::incidentEdges(Vertex v, EdgeList& edgelst) Graph::Edge e; EdgeItor eitor; int vtx_id = v.getid(); eitor = padjlstarray[vtx_id].begin(); while (eitor!= padjlstarray[vtx_id].end()) edgelst.push_back(*eitor); eitor++; void Graph::printGraph() int i, j; EdgeItor eitor; int numoutgoingedges; for (i=0; i<num_vertices; i++) cout << setw(2) << (char)(i+'a') << " "; numoutgoingedges = padjlstarray[i].size(); eitor = padjlstarray[i].begin(); DS 13-40

41 Graph.cpp (3) /** Graph.cpp (3) */ void Graph::incidentEdges(Vertex v, EdgeList& edgelst) Graph::Edge e; EdgeItor eitor; int vtx_id = v.getid(); eitor = padjlstarray[vtx_id].begin(); while (eitor!= padjlstarray[vtx_id].end()) edgelst.push_back(*eitor); eitor++; DS 13-41

42 Graph.cpp (4) /** Graph.cpp (4) */ void Graph::printGraph() int i, j; EdgeItor eitor; int numoutgoingedges; for (i=0; i<num_vertices; i++) cout << setw(2) << (char)(i+'a') << " "; numoutgoingedges = padjlstarray[i].size(); eitor = padjlstarray[i].begin(); while (eitor!= padjlstarray[i].end()) cout << *eitor << " "; eitor++; cout << endl; DS 13-42

43 DepthFirstSearch.h (1) /** DepthFirstSearch.h (1)*/ #ifndef DEPTHFIRSTSEARCH_H #define DEPTHFIRSTSEARCH_H #include <iostream> #include "Graph.h" using namespace std; class DepthFirstSearch protected: typedef Graph::Vertex Vertex; typedef Graph::Edge Edge; typedef std::list<graph::vertex> VertexList; typedef std::list<graph::edge> EdgeList; protected: Graph& graph; Vertex start; bool done; // flag of search done protected: void initialize(); void dfstraversal(vertex& v, Vertex& target, VertexList& path); virtual void traversediscovery(const Edge& e, const Vertex& from) virtual void traverseback(const Edge& e, const Vertex& from) virtual void finishvisit(const Vertex& v) virtual bool isdone() const return done; DS 13-43

44 DepthFirstSearch.h (2) /** DepthFirstSearch.h (2)*/ // marking utilities void visit(vertex& v); void visit(edge& e); void unvisit(vertex& v); void unvisit(edge& e); bool isvisited(vertex& v); bool isvisited(edge& e); void setedgestatus(edge& e, EdgeStatus es); EdgeStatus getedgestatus(edge& e); public: DepthFirstSearch(Graph& g); void findpath(vertex& s, Vertex& t, VertexList& path); Graph& getgraph() return graph; void showconnectivity(); private: VertexStatus* pvrtxstatus; EdgeStatus** ppedgestatus; int** ppconnectivity; ; #endif DS 13-44

45 DepthFirstSearch.cpp (1) /** DepthFirstSearch.cpp (1)*/ #include <iostream> #include <list> #include <algorithm> #include "Graph.h" #include "DepthFirstSearch.h" using namespace std; typedef Graph::Vertex Vertex; typedef Graph::Edge Edge; typedef std::list<graph::vertex> VertexList; typedef std::list<graph::vertex>::iterator VertexItor; typedef std::list<graph::edge> EdgeList; typedef std::list<graph::edge>::iterator EdgeItor; DepthFirstSearch::DepthFirstSearch(Graph& g) :graph(g) int num_nodes = graph.getnumvertices(); pvrtxstatus = new VertexStatus[num_nodes]; for (int i=0; i<num_nodes; i++) pvrtxstatus[i] = UN_VISITED; ppedgestatus = new EdgeStatus*[num_nodes]; for (int i=0; i<num_nodes; i++) ppedgestatus[i] = new EdgeStatus[num_nodes]; for (int i=0; i<num_nodes; i++) for (int j=0; j<num_nodes; j++) ppedgestatus[i][j] = EDGE_UN_VISITED; DS 13-45

46 DepthFirstSearch.cpp (2) /** DepthFirstSearch.cpp (2)*/ ppconnectivity = new int*[num_nodes]; for (int i=0; i<num_nodes; i++) ppconnectivity[i] = new int[num_nodes]; for (int i=0; i<num_nodes; i++) for (int j=0; j<num_nodes; j++) ppconnectivity[i][j] = PLUS_INF; // initially not connected Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; EdgeList edges; edges.clear(); graph.edges(edges); for (EdgeItor pe = edges.begin(); pe!= edges.end(); ++pe) vtx_1 = (*pe).getvertex_1(); vtx_1_id = vtx_1.getid(); vtx_2 = (*pe).getvertex_2(); vtx_2_id = vtx_2.getid(); ppconnectivity[vtx_1_id][vtx_2_id] = (*pe).getdistance(); for (int i=0; i<num_nodes; i++) ppconnectivity[i][i] = 0; // distance of same node DS 13-46

47 DepthFirstSearch.cpp (3) /** DepthFirstSearch.cpp (3)*/ void DepthFirstSearch::initialize() int num_nodes = graph.getnumvertices(); VertexList verts; graph.vertices(verts); Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; done = false; for (int i=0; i<num_nodes; i++) pvrtxstatus[i] = UN_VISITED; for (int i=0; i<num_nodes; i++) for (int j=0; j<num_nodes; j++) ppedgestatus[i][j] = EDGE_UN_VISITED; DS 13-47

48 DepthFirstSearch.cpp (4) /** DepthFirstSearch.cpp (4)*/ void DepthFirstSearch::showConnectivity() int num_nodes = graph.getnumvertices(); int dist; cout << "Connectivity of graph: " << endl; cout << " "; for (int i=0; i<num_nodes; i++) cout << setw(5) << (char)(i + 'A'); cout << endl; cout << "-----+"; for (int i=0; i<num_nodes; i++) cout << "-----"; cout << endl; for (int i=0; i<num_nodes; i++) cout << " " << (char)(i + 'A') << " "; for (int j=0; j<num_nodes; j++) dist = ppconnectivity[i][j]; if (dist == PLUS_INF) cout << " +oo"; else cout << setw(5) << dist; cout << endl; DS 13-48

49 DepthFirstSearch.cpp (5) /** DepthFirstSearch.cpp (5)*/ void DepthFirstSearch::dfsTraversal(Vertex& v, Vertex& target, VertexList& path) visit(v); if (v == target) done = true; return; EdgeList incidentedges; incidentedges.clear(); graph.incidentedges(v, incidentedges); EdgeItor pe = incidentedges.begin(); while (!isdone() && pe!= incidentedges.end()) Edge e = *pe++; EdgeStatus estat = getedgestatus(e); if (estat == EDGE_UN_VISITED) visit(e); Vertex w = e.opposite(v); if (!isvisited(w)) //traversediscovery(e, v); path.push_back(w); setedgestatus(e, DISCOVERY); if (!isdone()) dfstraversal(w, target, path); if (!isdone()) //traverseback(e, v); // erase some possible cycle Vertex last_pushed = path.back(); // for debugging path.pop_back(); DS 13-49

50 DepthFirstSearch.cpp (6) /** DepthFirstSearch.cpp (6)*/ else setedgestatus(e, BACK); // end of processing of all incident edges //template<typename G> void DepthFirstSearch::findPath(Vertex &start, Vertex &target, VertexList& path) initialize(); path.clear(); path.push_back(start); dfstraversal(start, target, path); void DepthFirstSearch::visit(Vertex& v) Graph::Vertex* pvtx; int numnodes = getgraph().getnumvertices(); int vtx_id = v.getid(); if (vtx_id >= 0 && vtx_id < numnodes) pvrtxstatus[vtx_id] = VISITED; else cout << "Vertex (" << v << ") ID is out-of-range (" ; cout << numnodes << ")" << endl; Yeungnam University (YU-ANTL) DS 13-50

51 DepthFirstSearch.cpp (7) /** DepthFirstSearch.cpp (7)*/ void DepthFirstSearch::visit(Edge& e) Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; int numnodes = getgraph().getnumvertices(); vtx_1 = e.getvertex_1(); vtx_1_id = vtx_1.getid(); vtx_2 = e.getvertex_2(); vtx_2_id = vtx_2.getid(); if ((vtx_1_id >= 0 && vtx_1_id < numnodes) && (vtx_2_id >= 0 && vtx_2_id < numnodes)) ppedgestatus[vtx_1_id][vtx_2_id] = EDGE_VISITED; else cout << "Vertex IDs (" << vtx_1_id << ", " << vtx_2_id; cout << ") of Edge (" << e << ") is out-of-range (" << numnodes << ")" << endl; void DepthFirstSearch::unvisit(Vertex& v) Graph::Vertex* pvtx; int numnodes = getgraph().getnumvertices(); int vtx_id = v.getid(); if (vtx_id >= 0 && vtx_id < numnodes) pvrtxstatus[vtx_id] = UN_VISITED; else cout << "Vertex (" << v << ") ID is out-of-range (" << numnodes << ")" << endl; DS 13-51

52 DepthFirstSearch.cpp (8) /** DepthFirstSearch.cpp (8)*/ void DepthFirstSearch::unvisit(Edge& e) Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; int numnodes = getgraph().getnumvertices(); vtx_1 = e.getvertex_1(); vtx_1_id = vtx_1.getid(); vtx_2 = e.getvertex_2(); vtx_2_id = vtx_2.getid(); if ((vtx_1_id >= 0 && vtx_1_id < numnodes) && (vtx_2_id >= 0 && vtx_2_id < numnodes)) ppedgestatus[vtx_1_id][vtx_2_id] = EDGE_UN_VISITED; else cout << "Vertex IDs (" << vtx_1_id << ", " << vtx_2_id << ") of Edge ( ; cout << e << ") is out-of-range (" << numnodes << ")" << endl; DS 13-52

53 DepthFirstSearch.cpp (9) /** DepthFirstSearch.cpp (9)*/ bool DepthFirstSearch::isVisited(Vertex& v) Graph::Vertex* pvtx; int numnodes = getgraph().getnumvertices(); int vtx_id = v.getid(); if (vtx_id >= 0 && vtx_id < numnodes) return (pvrtxstatus[vtx_id] == VISITED); else cout << "Vertex (" << v << ") ID is out-of-range (" << numnodes << ")" << endl; return false; DS 13-53

54 DepthFirstSearch.cpp (10) /** DepthFirstSearch.cpp (10)*/ bool DepthFirstSearch::isVisited(Edge& e) Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; EdgeStatus estat; int numnodes = getgraph().getnumvertices(); vtx_1 = e.getvertex_1(); vtx_1_id = vtx_1.getid(); vtx_2 = e.getvertex_2(); vtx_2_id = vtx_2.getid(); if ((vtx_1_id >= 0 && vtx_1_id < numnodes) && (vtx_2_id >= 0 && vtx_2_id < numnodes)) estat = ppedgestatus[vtx_1_id][vtx_2_id]; if ((estat == EDGE_VISITED) (estat == DISCOVERY) (estat == BACK)) return true; else return false; else cout << "Vertex IDs (" << vtx_1_id << ", " << vtx_2_id << ") of Edge ( ; cout << e << ") is out-of-range (" << numnodes << ")" << endl; return false; DS 13-54

55 DepthFirstSearch.cpp (11) /** DepthFirstSearch.cpp (11)*/ void DepthFirstSearch::setEdgeStatus(Edge& e, EdgeStatus es) Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; int numnodes = getgraph().getnumvertices(); vtx_1 = e.getvertex_1(); vtx_1_id = vtx_1.getid(); vtx_2 = e.getvertex_2(); vtx_2_id = vtx_2.getid(); if ((vtx_1_id >= 0 && vtx_1_id < numnodes) && (vtx_2_id >= 0 && vtx_2_id < numnodes)) ppedgestatus[vtx_1_id][vtx_2_id] = es; else cout << "Vertex IDs (" << vtx_1_id << ", " << vtx_2_id << ") of Edge ( ; cout << e << ") is out-of-range (" << numnodes << ")" << endl; DS 13-55

56 DepthFirstSearch.cpp (12) /** DepthFirstSearch.cpp (12)*/ EdgeStatus DepthFirstSearch::getEdgeStatus(Edge& e) Vertex vtx_1, vtx_2; int vtx_1_id, vtx_2_id; int numnodes = getgraph().getnumvertices(); EdgeStatus estat; vtx_1 = e.getvertex_1(); vtx_1_id = vtx_1.getid(); vtx_2 = e.getvertex_2(); vtx_2_id = vtx_2.getid(); if ((vtx_1_id >= 0 && vtx_1_id < numnodes) && (vtx_2_id >= 0 && vtx_2_id < numnodes)) estat = ppedgestatus[vtx_1_id][vtx_2_id]; return estat; else cout << "Edge (" << e << ") was not found from AdjacencyList" << endl; return EDGE_NOT_FOUND; DS 13-56

57 Fig Example of depth-first search traversal on a graph starting at vertex A. Discovery edges are shown with solid lines and back edges are shown with dashed lines: DS 13-57

58 main.cpp (1) /** main.cpp (1) */ #include <iostream> #include <string> //#include "Vertex.h" //#include "Edge.h" #include "Graph.h" #include "DepthFirstSearch.h" #include "BreadthFirstSearch.h" #define NUM_NODES 16 #define NUM_EDGES 50 typedef Graph::Vertex Vertex; typedef Graph::Edge Edge; typedef std::list<graph::vertex> VtxList; typedef std::list<graph::edge> EdgeList; typedef std::list<graph::vertex>::iterator VtxItor; typedef std::list<graph::edge>::iterator EdgeItor; void main() Vertex v[num_nodes] = // Topology of Figure 13.6 (p. 608) Vertex("A", 0, UN_VISITED), Vertex("B", 1, UN_VISITED), Vertex("C", 2, UN_VISITED), Vertex("D", 3, UN_VISITED), Vertex("E", 4, UN_VISITED), Vertex("F", 5, UN_VISITED), Vertex("G", 6, UN_VISITED), Vertex("H", 7, UN_VISITED), Vertex("I", 8, UN_VISITED), Vertex("J", 9, UN_VISITED), Vertex("K", 10, UN_VISITED), Vertex("L", 11, UN_VISITED), Vertex("M", 12, UN_VISITED), Vertex("N", 13, UN_VISITED), Vertex("0", 14, UN_VISITED), Vertex("P", 15, UN_VISITED) ; DS 13-58

59 main.cpp (2) /** main.cpp (2) */ Graph::Edge edges[num_edges] = Edge(v[0], v[1], 10), Edge(v[1], v[0], 10), Edge(v[0], v[4], 10), Edge(v[4], v[0], 10), Edge(v[0], v[5], 15), Edge(v[5], v[0], 15), Edge(v[1], v[2], 10), Edge(v[2], v[1], 10), Edge(v[1], v[5], 10), Edge(v[5], v[1], 10), Edge(v[2], v[3], 10), Edge(v[3], v[2], 10), Edge(v[2], v[6], 10), Edge(v[6], v[2], 10), Edge(v[3], v[6], 15), Edge(v[6], v[3], 15), Edge(v[3], v[7], 10), Edge(v[7], v[3], 10), Edge(v[4], v[5], 10), Edge(v[5], v[4], 10), Edge(v[4], v[8], 10), Edge(v[8], v[4], 10), Edge(v[5], v[8], 15), Edge(v[8], v[5], 15), Edge(v[6], v[9], 15), Edge(v[9], v[6], 15), Edge(v[6], v[10], 10), Edge(v[10], v[6], 10), Edge(v[6], v[11], 15), Edge(v[11], v[6], 15), Edge(v[7], v[11], 10), Edge(v[11], v[7], 10), Edge(v[8], v[9], 10), Edge(v[9], v[8], 10), Edge(v[8], v[12], 10), Edge(v[12], v[8], 10), Edge(v[8], v[13], 15), Edge(v[13], v[8], 15), Edge(v[9], v[10], 10), Edge(v[10], v[9], 10), Edge(v[10], v[13], 15), Edge(v[13], v[10], 15), Edge(v[10], v[14], 10), Edge(v[14], v[10], 10), Edge(v[11], v[15], 10), Edge(v[15], v[11], 10), Edge(v[12], v[13], 10), Edge(v[13], v[12], 10), Edge(v[14], v[15], 10), Edge(v[15], v[14], 10) ; Graph simplegraph(num_nodes); DS 13-59

60 main.cpp (3) /** main.cpp (3) */ Graph simplegraph(num_nodes); cout << "Inserting vertices.." << endl; for (int i=0; i<num_nodes; i++) simplegraph.insertvertex(v[i]); VtxList vtxlst; simplegraph.vertices(vtxlst); int count = 0; cout << "Inserted vertices: "; for (VtxItor vitor = vtxlst.begin(); vitor!= vtxlst.end(); ++vitor) cout << *vitor << " "; cout << endl; cout << "Inserting edges.." << endl; for (int i=0; i<num_edges; i++) simplegraph.insertedge(edges[i]); cout << "Inserted edges: " << endl; count = 0; EdgeList eglst; simplegraph.edges(eglst); DS 13-60

61 main.cpp (4) /** main.cpp (4) */ for (EdgeItor p = eglst.begin(); p!= eglst.end(); ++p) count++; cout << *p << ", "; if (count % 5 == 0) cout << endl; cout << endl; cout << "Print out Graph based on Adjacency List.." << endl; simplegraph.printgraph(); cout << "Testing dfsgraph..." << endl; DepthFirstSearch dfsgraph(simplegraph); VtxList path; dfsgraph.findpath(v[0], v[15], path); cout << "Path (" << v[0] << " => " << v[15] << ) : "; for (VtxItor vitor = path.begin(); vitor!= path.end(); ++vitor) cout << *vitor << " "; cout << endl; dfsgraph.findpath(v[15], v[0], path); cout << "Path (" << v[15] << " => " << v[0] << ) : "; for (VtxItor vitor = path.begin(); vitor!= path.end(); ++vitor) cout << *vitor << " "; cout << endl; DS 13-61

62 Example output (1) DS 13-62

63 Example output (2) DS 13-63

Graphs 3/25/14 15:37 SFO LAX Goodrich, Tamassia, Goldwasser Graphs 2

Graphs 3/25/14 15:37 SFO LAX Goodrich, Tamassia, Goldwasser Graphs 2 Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Graphs SFO 337 LAX 1843 1743 1233 802 DFW

More information

Data Structures Lecture 14

Data Structures Lecture 14 Fall 2018 Fang Yu Software Security Lab. ept. Management Information Systems, National hengchi University ata Structures Lecture 14 Graphs efinition, Implementation and Traversal Graphs Formally speaking,

More information

Design Project IP Packet Router Simulation -

Design Project IP Packet Router Simulation - 2013-2 Design Project IP Packet Router Simulation - December 10, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, College of Engineering, Yeungnam University, KOREA

More information

Graphs ORD SFO LAX DFW. Data structures and Algorithms

Graphs ORD SFO LAX DFW. Data structures and Algorithms SFO 143 ORD 337 1743 02 Graphs LAX 1233 DFW Data structures and Algorithms Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++ Goodrich, Tamassia and

More information

Graphs ADTs and Implementations

Graphs ADTs and Implementations Graphs ADTs and Implementations SFO 337 1843 802 ORD LAX 1233 DFW - 1 - Applications of Graphs Ø Electronic circuits cslab1a cslab1b q Printed circuit board math.brown.edu q Integrated circuit Ø Transportation

More information

Graphs ORD SFO LAX DFW. Graphs 1

Graphs ORD SFO LAX DFW. Graphs 1 Graphs ORD 1843 SFO 802 1743 337 1233 LAX DFW Graphs 1 Outline and Reading Graphs ( 12.1) Definition Applications Terminology Properties ADT Data structures for graphs ( 12.2) Edge list structure Adjacency

More information

CHAPTER 13 GRAPH ALGORITHMS

CHAPTER 13 GRAPH ALGORITHMS CHPTER 13 GRPH LGORITHMS SFO LX ORD DFW 1 CKNOWLEDGEMENT: THESE SLIDES RE DPTED FROM SLIDES PROVIDED WITH DT STRUCTURES ND LGORITHMS IN C++, GOODRICH, TMSSI ND MOUNT (WILEY 2004) ND SLIDES FROM JORY DENNY

More information

Graph Terminology and Representations

Graph Terminology and Representations Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 Graph Terminology and Representations 1 Graphs A graph is a pair (V, E), where

More information

Depth-First Search and Template Patterns

Depth-First Search and Template Patterns Depth-First Search and Template Patterns A B D E C 1 Outline Template Patterns and Search Depth-first search Algorithm Example Properties Analysis Applications of DFS Path finding Cycle finding CS 4407,

More information

Depth-First Search A B D E C

Depth-First Search A B D E C epth-first Search Outline and Reading efinitions (6.1) Subgraph onnectivity Spanning trees and forests epth-first search (6.3.1) lgorithm xample Properties nalysis pplications of FS (6.5) Path finding

More information

Graphs ORD SFO LAX DFW Goodrich, Tamassia Graphs 1

Graphs ORD SFO LAX DFW Goodrich, Tamassia Graphs 1 Graphs SFO 33 143 ORD 02 LAX 1233 DFW 2004 Goodrich, Tamassia Graphs 1 What is a Graph? (in computer science, it s not a data plot) General structure for representing positions with an arbitrary connectivity

More information

CHAPTER 14 GRAPH ALGORITHMS ORD SFO LAX DFW

CHAPTER 14 GRAPH ALGORITHMS ORD SFO LAX DFW SFO ORD CHAPTER 14 GRAPH ALGORITHMS LAX DFW ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) GRAPH

More information

Lecture 14: Graph Representation, DFS and Applications

Lecture 14: Graph Representation, DFS and Applications Lecture 14: Graph Representation, FS and pplications SFO OR LX FW ourtesy to Goodrich, Tamassia and Olga Veksler Instructor: Yuzhen Xie Outline Graph Representation dge List djacency List djacency Matrix

More information

Graph ADT. Lecture18: Graph II. Adjacency Matrix. Representation of Graphs. Data Vertices and edges. Methods

Graph ADT. Lecture18: Graph II. Adjacency Matrix. Representation of Graphs. Data Vertices and edges. Methods Graph T S33: ata Structures (0) Lecture8: Graph II ohyung Han S, POSTH bhhan@postech.ac.kr ata Vertices and edges endvertices(e): an array of the two endvertices of e opposite(v,e): the vertex opposite

More information

Graph Terminology and Representations

Graph Terminology and Representations Presetatio for use with the textbook, Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Graph Termiology ad Represetatios 2015 Goodrich ad Tamassia Graphs 1 Graphs A graph is

More information

Graphs. CS16: Introduction to Data Structures & Algorithms Spring 2018

Graphs. CS16: Introduction to Data Structures & Algorithms Spring 2018 Graphs CS16: Introduction to Data Structures & Algorithms Spring 2018 Outline What is a Graph Terminology Properties Graph Types Representations Performance BFS/DFS Applications 2 What is a Graph A graph

More information

Winter 2016 COMP-250: Introduction to Computer Science. Lecture 16, March 10, 2016

Winter 2016 COMP-250: Introduction to Computer Science. Lecture 16, March 10, 2016 Winter 2016-250: Introduction to Computer Science Lecture 16, March 10, 2016 GRAPHS Definitions Examples The Graph ADT PVD HNL LAX DFW STL FTL What is a Graph? Agraph G = (V,E) is composed of: V: set of

More information

Graphs ORD SFO LAX DFW

Graphs ORD SFO LAX DFW Graphs SFO 337 1843 802 ORD LAX 1233 DFW Graphs A graph is a pair (V, E), where V is a set of odes, called vertices E is a collectio of pairs of vertices, called edges Vertices ad edges are positios ad

More information

Breadth-First Search L 1 L Goodrich, Tamassia, Goldwasser Breadth-First Search 1

Breadth-First Search L 1 L Goodrich, Tamassia, Goldwasser Breadth-First Search 1 readth-irst Search 2013 Goodrich, Tamassia, Goldwasser readth-irst Search 1 readth-irst Search readth-first search (S) is a general technique for traversing a graph S traversal of a graph G Visits all

More information

CS 225. April 16 Graph Traversal. Data Structures. Wade Fagen-Ulmschneider

CS 225. April 16 Graph Traversal. Data Structures. Wade Fagen-Ulmschneider CS 225 Data Structures April 16 Graph Traversal Wade Fagen-Ulmschneider Graph ADT Data: - Vertices - Edges - Some data structure maintaining the structure between vertices and edges. d V W f b e X Y g

More information

Directed Graphs BOS Goodrich, Tamassia Directed Graphs 1 ORD JFK SFO DFW LAX MIA

Directed Graphs BOS Goodrich, Tamassia Directed Graphs 1 ORD JFK SFO DFW LAX MIA Directed Graphs BOS ORD JFK SFO LAX DFW MIA 2010 Goodrich, Tamassia Directed Graphs 1 Digraphs A digraph is a graph whose edges are all directed Short for directed graph Applications one-way streets flights

More information

DFS on Directed Graphs BOS. Outline and Reading ( 6.4) Digraphs. Reachability ( 6.4.1) Directed Acyclic Graphs (DAG s) ( 6.4.4)

DFS on Directed Graphs BOS. Outline and Reading ( 6.4) Digraphs. Reachability ( 6.4.1) Directed Acyclic Graphs (DAG s) ( 6.4.4) S on irected Graphs OS OR JK SO LX W MI irected Graphs S 1.3 1 Outline and Reading ( 6.4) Reachability ( 6.4.1) irected S Strong connectivity irected cyclic Graphs (G s) ( 6.4.4) Topological Sorting irected

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Graphs - Introduction Kostas Alexis Terminology In the context of our course, graphs represent relations among data items G = {V,E} A graph is a set of vertices

More information

Lecture 16: Directed Graphs

Lecture 16: Directed Graphs Lecture 16: Directed Graphs ORD JFK BOS SFO LAX DFW MIA Courtesy of Goodrich, Tamassia and Olga Veksler Instructor: Yuzhen Xie Outline Directed Graphs Properties Algorithms for Directed Graphs DFS and

More information

DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries

DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries 2013-2 DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 22, 2013 Advanced

More information

Graph Algorithms shortest paths, minimum spanning trees, etc.

Graph Algorithms shortest paths, minimum spanning trees, etc. Graph Algorithms shortest paths, minimum spanning trees, etc. SFO ORD LAX DFW Graphs 1 Outline and Reading Graphs ( 1.1) Definition Applications Terminology Properties ADT Data structures for graphs (

More information

Graph Algorithms shortest paths, minimum spanning trees, etc.

Graph Algorithms shortest paths, minimum spanning trees, etc. SFO ORD LAX Graph Algorithms shortest paths, minimum spanning trees, etc. DFW Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University Acknowledgement: These slides are adapted from slides provided with

More information

CHAPTER 13 GRAPH ALGORITHMS ORD SFO LAX DFW

CHAPTER 13 GRAPH ALGORITHMS ORD SFO LAX DFW SFO ORD CHAPTER 13 GRAPH ALGORITHMS LAX DFW ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES

More information

CHAPTER 13 GRAPH ALGORITHMS

CHAPTER 13 GRAPH ALGORITHMS CHAPTER 13 GRAPH ALGORITHMS SFO LAX ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 00) AND SLIDES FROM NANCY

More information

Graphs Weighted Graphs. Reading: 12.5, 12.6, 12.7

Graphs Weighted Graphs. Reading: 12.5, 12.6, 12.7 Graphs Weighted Graphs Reading: 1.5, 1.6, 1. Weighted Graphs, a.k.a. Networks In a weighted graph, each edge has an associated numerical value, called the weight or cost of the edge Edge weights may represent,

More information

Shortest Paths D E. Shortest Paths 1

Shortest Paths D E. Shortest Paths 1 Shortest Paths A 2 7 2 B C D 2 E F Shortest Paths Outline and Reading Weighted graphs ( 7.) Shortest path problem Shortest path properties Dijkstra s algorithm ( 7..) Algorithm Edge relaxation The Bellman-Ford

More information

Suggested Study Strategy

Suggested Study Strategy Final Exam Thursday, 7 August 2014,19:00 22:00 Closed Book Will cover whole course, with emphasis on material after midterm (hash tables, binary search trees, sorting, graphs) Suggested Study Strategy

More information

Dijkstra s Algorithm

Dijkstra s Algorithm Dijkstra s Algorithm 7 1 3 1 Weighted Graphs In a weighted graph, each edge has an associated numerical value, called the weight of the edge Edge weights may represent, distances, costs, etc. Example:

More information

DataStruct 7. Trees. Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011.

DataStruct 7. Trees. Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. 2013-2 DataStruct 7. Trees Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 6, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept.

More information

DataStruct 8. Heaps and Priority Queues

DataStruct 8. Heaps and Priority Queues 2013-2 DataStruct 8. Heaps and Priority Queues Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 13, 2013 Advanced Networking Technology

More information

Graph Algorithms. Textbook reading. Chapter 3 Chapter 4. CSci 3110 Graph Algorithms 1/41

Graph Algorithms. Textbook reading. Chapter 3 Chapter 4. CSci 3110 Graph Algorithms 1/41 CSci 3110 Graph Algorithms 1/41 Graph Algorithms Textbook reading Chapter 3 Chapter 4 CSci 3110 Graph Algorithms 2/41 Overview Design principle: Learn the structure of a graph by systematic exploration

More information

Chapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1

Chapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs 2011 Pearson Addison-Wesley. All rights reserved 14 A-1 Terminology G = {V, E} A graph G consists of two sets A set V of vertices, or nodes A set E of edges A subgraph Consists of a subset

More information

國立清華大學電機工程學系. Outline

國立清華大學電機工程學系. Outline 國立清華大學電機工程學系 EE Data Structure Chapter Graph (Part I) Outline The Graph Abstract Data Type Introduction Definitions Graph Representations Elementary Graph Operations Minimum Cost Spanning Trees ch.- River

More information

Ch 8. Operator Overloading, Friends, and References

Ch 8. Operator Overloading, Friends, and References 2014-1 Ch 8. Operator Overloading, Friends, and References May 28, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel

More information

Digraphs ( 12.4) Directed Graphs. Digraph Application. Digraph Properties. A digraph is a graph whose edges are all directed.

Digraphs ( 12.4) Directed Graphs. Digraph Application. Digraph Properties. A digraph is a graph whose edges are all directed. igraphs ( 12.4) irected Graphs OR OS digraph is a graph whose edges are all directed Short for directed graph pplications one- way streets flights task scheduling irected Graphs 1 irected Graphs 2 igraph

More information

Applications of BFS and DFS

Applications of BFS and DFS pplications of S and S S all // : PM Some pplications of S and S S o find the shortest path from a vertex s to a vertex v in an unweighted graph o find the length of such a path o construct a S tree/forest

More information

Graphs. Data Structures 1 Graphs

Graphs. Data Structures 1 Graphs Graphs Graph Applications Definitions Graph Representations(adjacency matrix/list) Graph ADT Graph Traversals: BFS, DFS Shortest Path Algorithms Minimum Spanning Tree Algorithms Data Structures Graphs

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information

Graph Theory. Many problems are mapped to graphs. Problems. traffic VLSI circuits social network communication networks web pages relationship

Graph Theory. Many problems are mapped to graphs. Problems. traffic VLSI circuits social network communication networks web pages relationship Graph Graph Usage I want to visit all the known famous places starting from Seoul ending in Seoul Knowledge: distances, costs Find the optimal(distance or cost) path Graph Theory Many problems are mapped

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

CS 220: Discrete Structures and their Applications. graphs zybooks chapter 10

CS 220: Discrete Structures and their Applications. graphs zybooks chapter 10 CS 220: Discrete Structures and their Applications graphs zybooks chapter 10 directed graphs A collection of vertices and directed edges What can this represent? undirected graphs A collection of vertices

More information

Graph Algorithms Using Depth First Search

Graph Algorithms Using Depth First Search Graph Algorithms Using Depth First Search Analysis of Algorithms Week 8, Lecture 1 Prepared by John Reif, Ph.D. Distinguished Professor of Computer Science Duke University Graph Algorithms Using Depth

More information

Lecture 9 Graph Traversal

Lecture 9 Graph Traversal Lecture 9 Graph Traversal Euiseong Seo (euiseong@skku.edu) SWE00: Principles in Programming Spring 0 Euiseong Seo (euiseong@skku.edu) Need for Graphs One of unifying themes of computer science Closely

More information

Routing & Congestion Control

Routing & Congestion Control WIDE AREA NETWORK Routing & Congestion Control Introduction Congestion control and routing are major issues to be handled in Wide Area Networks. Congestion is handled at transport layer and routing is

More information

Definition Example Solution

Definition Example Solution Section 11.4 Spanning Trees Definition: Let G be a simple graph. A spanning tree of G is a subgraph of G that is a tree containing every vertex of G. Example: Find the spanning tree of this simple graph:

More information

Graphs. The ultimate data structure. graphs 1

Graphs. The ultimate data structure. graphs 1 Graphs The ultimate data structure graphs 1 Definition of graph Non-linear data structure consisting of nodes & links between them (like trees in this sense) Unlike trees, graph nodes may be completely

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

COP 4531 Complexity & Analysis of Data Structures & Algorithms

COP 4531 Complexity & Analysis of Data Structures & Algorithms COP Complexity & Analysis of Data Structures & Algorithms Overview of Graphs Breadth irst Search, and Depth irst Search hanks to several people who contributed to these slides including Piyush Kumar and

More information

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list UNIT-4 Graph: Terminology, Representation, Traversals Applications - spanning trees, shortest path and Transitive closure, Topological sort. Sets: Representation - Operations on sets Applications. 1. Name

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

Minimum Spanning Trees Ch 23 Traversing graphs

Minimum Spanning Trees Ch 23 Traversing graphs Next: Graph Algorithms Graphs Ch 22 Graph representations adjacency list adjacency matrix Minimum Spanning Trees Ch 23 Traversing graphs Breadth-First Search Depth-First Search 11/30/17 CSE 3101 1 Graphs

More information

Module 11: Additional Topics Graph Theory and Applications

Module 11: Additional Topics Graph Theory and Applications Module 11: Additional Topics Graph Theory and Applications Topics: Introduction to Graph Theory Representing (undirected) graphs Basic graph algorithms 1 Consider the following: Traveling Salesman Problem

More information

Paths. Path is a sequence of edges that begins at a vertex of a graph and travels from vertex to vertex along edges of the graph.

Paths. Path is a sequence of edges that begins at a vertex of a graph and travels from vertex to vertex along edges of the graph. Paths Path is a sequence of edges that begins at a vertex of a graph and travels from vertex to vertex along edges of the graph. Formal Definition of a Path (Undirected) Let n be a nonnegative integer

More information

GRAPHS (Undirected) Graph: Set of objects with pairwise connections. Why study graph algorithms?

GRAPHS (Undirected) Graph: Set of objects with pairwise connections. Why study graph algorithms? GRAPHS (Undirected) Graph: Set of objects with pairwise connections. Why study graph algorithms? Interesting and broadly useful abstraction. Challenging branch of computer science and discrete math. Hundreds

More information

Graphs ADT and Traversing

Graphs ADT and Traversing Steven J. Zeil July 31, 2013 Contents 1 A Graph ADT 3 1.1 Vertex...................................... 4 1.2 Edge....................................... 7 1.3 DiGraph....................................

More information

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this Lecture Notes Array Review An array in C++ is a contiguous block of memory. Since a char is 1 byte, then an array of 5 chars is 5 bytes. For example, if you execute the following C++ code you will allocate

More information

Copyright 2000, Kevin Wayne 1

Copyright 2000, Kevin Wayne 1 Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. Directed

More information

Unweighted Graphs & Algorithms

Unweighted Graphs & Algorithms Unweighted Graphs & Algorithms Zachary Friggstad Programming Club Meeting References Chapter 4: Graph (Section 4.2) Chapter 22: Elementary Graph Algorithms Graphs Features: vertices/nodes/dots and edges/links/lines

More information

To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem

To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem CHAPTER 24 Graphs and Applications Objectives To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem ( 24.1). To describe graph terminologies: vertices, edges, simple

More information

CS2210 Data Structures and Algorithms

CS2210 Data Structures and Algorithms S1 ata Structures and Algorithms Lecture 1 : Shortest Paths A 4 1 5 5 3 4 Goodrich, Tamassia Outline Weighted Graphs Shortest Paths Algorithm (ijkstra s) Weighted Graphs ach edge has an associated numerical

More information

Big O Notation and Graphs. CMSC Week 9

Big O Notation and Graphs. CMSC Week 9 Big O Notation and Graphs CMSC 132 - Week 9 Graphs API A graph is a pair (V, E), where V is a set of nodes, called vertices E is a collection of pairs of vertices, called edges Vertices and edges can be

More information

CSCI 136 Data Structures & Advanced Programming

CSCI 136 Data Structures & Advanced Programming CSCI 136 Data Structures & Advanced Programming Lecture 29 Fall 2018 Instructors: Bill J Bill L Bill L Bill J Last Time Recursive Depth-First Search Tips on writing recursive methods Graph Data Structures:

More information

UNIT 5 GRAPH. Application of Graph Structure in real world:- Graph Terminologies:

UNIT 5 GRAPH. Application of Graph Structure in real world:- Graph Terminologies: UNIT 5 CSE 103 - Unit V- Graph GRAPH Graph is another important non-linear data structure. In tree Structure, there is a hierarchical relationship between, parent and children that is one-to-many relationship.

More information

CSE 100: GRAPH ALGORITHMS

CSE 100: GRAPH ALGORITHMS CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges

More information

Lecture 17: Weighted Graphs, Dijkstra s Algorithm. Courtesy of Goodrich, Tamassia and Olga Veksler

Lecture 17: Weighted Graphs, Dijkstra s Algorithm. Courtesy of Goodrich, Tamassia and Olga Veksler Lecture 17: Weighted Graphs, Shortest Paths: Dijkstra s Algorithm A 4 B 7 C 1 D 3 5 3 9 5 E Courtesy of Goodrich, Tamassia and Olga Veksler Instructor: Yuzhen Xie Weighted Graphs In a weighted graph, each

More information

SELF-BALANCING SEARCH TREES. Chapter 11

SELF-BALANCING SEARCH TREES. Chapter 11 SELF-BALANCING SEARCH TREES Chapter 11 Tree Balance and Rotation Section 11.1 Algorithm for Rotation BTNode root = left right = data = 10 BTNode = left right = data = 20 BTNode NULL = left right = NULL

More information

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F)) DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES UNIT IV NONLINEAR DATA STRUCTURES Part A 1. Define Tree [N/D 08]

More information

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees Chapter 11 Copyright McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education. Chapter Summary Introduction to Trees Applications

More information

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value 1 Possible implementations Sorted linear implementations o Appropriate if

More information

Algorithm Design and Analysis

Algorithm Design and Analysis Algorithm Design and Analysis LECTURE 4 Graphs Definitions Traversals Adam Smith 9/8/10 Exercise How can you simulate an array with two unbounded stacks and a small amount of memory? (Hint: think of a

More information

CSE030 Fall 2012 Final Exam Friday, December 14, PM

CSE030 Fall 2012 Final Exam Friday, December 14, PM CSE030 Fall 2012 Final Exam Friday, December 14, 2012 3-6PM Write your name here and at the top of each page! Name: Select your lab session: Tuesdays Thursdays Paper. If you have any questions or need

More information

To list all vertices connected to a vertex u in graph G we can use the following loop:

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

More information

Outline. Introduction. Representations of Graphs Graph Traversals. Applications. Definitions and Basic Terminologies

Outline. Introduction. Representations of Graphs Graph Traversals. Applications. Definitions and Basic Terminologies Graph Chapter 9 Outline Introduction Definitions and Basic Terminologies Representations of Graphs Graph Traversals Breadth first traversal Depth first traversal Applications Single source shortest path

More information

Graph: representation and traversal

Graph: representation and traversal Graph: representation and traversal CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang! Acknowledgement The set of slides have use materials from the following resources Slides for textbook

More information

Konigsberg Bridge Problem

Konigsberg Bridge Problem Graphs Konigsberg Bridge Problem c C d g A Kneiphof e D a B b f c A C d e g D a b f B Euler s Graph Degree of a vertex: the number of edges incident to it Euler showed that there is a walk starting at

More information

Definition of Graphs and Trees. Representation of Trees.

Definition of Graphs and Trees. Representation of Trees. Definition of Graphs and Trees. Representation of Trees. Chapter 6 Definition of graphs (I) A directed graph or digraph is a pair G = (V,E) s.t.: V is a finite set called the set of vertices of G. E V

More information

Final Exam. CSE 2011 Prof. J. Elder Last Updated: :41 PM

Final Exam. CSE 2011 Prof. J. Elder Last Updated: :41 PM Final Exam Ø Tue, 17 Apr 2012 19:00 22:00 LAS B Ø Closed Book Ø Format similar to midterm Ø Will cover whole course, with emphasis on material after midterm (maps, hashing, binary search trees, sorting,

More information

DataStruct 5. Stacks, Queues, and Deques

DataStruct 5. Stacks, Queues, and Deques 2013-2 DataStruct 5. Stacks, Queues, and Deques Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. October 30, 2013 Advanced Networking Technology

More information

CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory

CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory Dustin Tseng Mike Li Wednesday January 16, 2006 Dustin Tseng Mike Li: CS490: Problem Solving in Computer Science, Lecture

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI. Department of Computer Science and Engineering CS6301 PROGRAMMING DATA STRUCTURES II

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI. Department of Computer Science and Engineering CS6301 PROGRAMMING DATA STRUCTURES II DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI Department of Computer Science and Engineering CS6301 PROGRAMMING DATA STRUCTURES II Anna University 2 & 16 Mark Questions & Answers Year / Semester: II / III

More information

12/5/17. trees. CS 220: Discrete Structures and their Applications. Trees Chapter 11 in zybooks. rooted trees. rooted trees

12/5/17. trees. CS 220: Discrete Structures and their Applications. Trees Chapter 11 in zybooks. rooted trees. rooted trees trees CS 220: Discrete Structures and their Applications A tree is an undirected graph that is connected and has no cycles. Trees Chapter 11 in zybooks rooted trees Rooted trees. Given a tree T, choose

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists Prof. amr Goneid, AUC 1 Linked Lists Prof. amr Goneid, AUC 2 Linked Lists The Linked List Structure Some Linked List

More information

Ch 6. Structures and Classes

Ch 6. Structures and Classes 2013-2 Ch 6. Structures and Classes September 1, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;

More information

Minimum Spanning Trees

Minimum Spanning Trees Minimum Spanning Trees 04 6 33 135 49 PVD 1 40 146 61 JFK 14 15 0 111 34 Minimum Spanning Trees 1 Outline and Reading Minimum Spanning Trees Definitions A crucial fact The Prim-Jarnik Algorithm Kruskal's

More information

3.1 Basic Definitions and Applications

3.1 Basic Definitions and Applications Graphs hapter hapter Graphs. Basic efinitions and Applications Graph. G = (V, ) n V = nodes. n = edges between pairs of nodes. n aptures pairwise relationship between objects: Undirected graph represents

More information

Graph Algorithms. Definition

Graph Algorithms. Definition Graph Algorithms Many problems in CS can be modeled as graph problems. Algorithms for solving graph problems are fundamental to the field of algorithm design. Definition A graph G = (V, E) consists of

More information

Undirected Graphs. V = { 1, 2, 3, 4, 5, 6, 7, 8 } E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 } n = 8 m = 11

Undirected Graphs. V = { 1, 2, 3, 4, 5, 6, 7, 8 } E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 } n = 8 m = 11 Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. V = {

More information

Basic Graph Definitions

Basic Graph Definitions CMSC 341 Graphs Basic Graph Definitions A graph G = (V,E) consists of a finite set of vertices, V, and a finite set of edges, E. Each edge is a pair (v,w) where v, w V. V and E are sets, so each vertex

More information

Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees. Iulian Năstac

Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees. Iulian Năstac Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees Iulian Năstac Recapitulation It is considered the following type: typedef struct nod { ; struct nod *next; } NOD; 2 Circular

More information

Data Structures. Elementary Graph Algorithms BFS, DFS & Topological Sort

Data Structures. Elementary Graph Algorithms BFS, DFS & Topological Sort Data Structures Elementary Graph Algorithms BFS, DFS & Topological Sort 1 Graphs A graph, G = (V, E), consists of two sets: V is a finite non-empty set of vertices. E is a set of pairs of vertices, called

More information

Part VI Graph algorithms. Chapter 22 Elementary Graph Algorithms Chapter 23 Minimum Spanning Trees Chapter 24 Single-source Shortest Paths

Part VI Graph algorithms. Chapter 22 Elementary Graph Algorithms Chapter 23 Minimum Spanning Trees Chapter 24 Single-source Shortest Paths Part VI Graph algorithms Chapter 22 Elementary Graph Algorithms Chapter 23 Minimum Spanning Trees Chapter 24 Single-source Shortest Paths 1 Chapter 22 Elementary Graph Algorithms Representations of graphs

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Ch 1. Algorithms and Basic C++ Programming

Ch 1. Algorithms and Basic C++ Programming 2013-2 Ch 1. Algorithms and Basic C++ Programming July 1, 2013 Dept. of Information & Communication Engineering College of Engineering Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742

More information