120 likes | 308 Views
Graphs. CIS 237 – Data Structures. Graphs - terminology. a set of vertices V ={v 1 , v 2 , v 3 , … , v m } a set of edges E= {e 1 , e 2 , e 3 , … , e n } Adjacent vertices Path Length Simple Cycle. Categories of Graphs. Graph connected disconnected complete
E N D
Graphs CIS 237 – Data Structures
Graphs - terminology • a set of vertices V ={v1, v2, v3, …, vm} • a set of edges E= {e1, e2, e3, …, en} • Adjacent vertices • Path • Length • Simple • Cycle
Categories of Graphs • Graph • connected • disconnected • complete • Directed Graph (diagraph) • in-degree • out-degree • directed path • weakly or strongly connected • Weighted
Breadth First Visit set<T> bfv() set<T> visitSet; for all vertices,v, in G { if v’s color is WHITE set v’s color to GRAY push v on Q while Q not empty { get u from front and pop Q set u’s color to BLACK visitSet.insert(u) for all vertices,w, adjacent to u (neighbors) { if w’s color is WHITE set w’s color to GRAY push u on Q } } }
dfv – depth first visit //returns true if cycle and false otherwise bool dfv(T v, list<T> &dfsList, bool cycleCheck) { for all vertices, u, adjacent to v { if u’s color is WHITE { set u’s color to GRAY if (dfv(u, dfsList, cycleCheck)) return true } else if (u’s color is GRAY and cycleCheck) return true } set v’s color to BLACK push_front v on list return false
Users of dfsVisit • Users • depth first visit • acyclic check • topological sort • Use • send a list • traverse the list on return or check return type
0 A 0 0 0 0 1 0 0 0 0 1 B 1 A D C B F E 0 0 0 1 C 1 0 0 0 0 0 0 0 D 1 E 0 1 0 0 0 0 0 F 0 0 0 0 Representation- Adjacency Matrix A B C D F E
B 7 A 7 3 1 B C 4 E 3 4 2 6 C 7 E 2 D 8 8 D E B F A C D E F 1 D 6 F D 7 Representation – Adjacency Set
Creating the Graph • Insert Vertex • vertices[v] = info • numVertices++ • Insert Edge • make sure the to and from vertex are there • create a neighbor with the to edge and weight • add neighbor to from vertex’s edge set • add to the to vertex’s inDegree • numEdges++
For all vertices in the graph…. vertexMap::iterator itr for (itr = vertices.begin(); itr != vertices.end(); itr++) process *itr Recall itr isiterator in a map (*itr).first ------ data (*itr).second ------ vertexInfo
For all vertices adjacent to v... set<neighbor<T> > friends = vertices[v].edges set<neighbor<T> >::iterator nitr; for (nitr =friends.begin(); nitr!=friends.end(); nitr++) process *nitr Recall nitr is an iterator in a set of neighbors (*nitr).data (*nitr).weight
With dfv bool dfv(T v, list<T> &dfsList, bool cycleCheck) { for (nitr=friends.begin(); nitr!=friends.end(); nitr++) { if (vertices[(*nitr).data].color == vertexInfo<T>::WHITE) { vertices[(*nitr).data].color = vertexInfo<T>::GRAY if (dfv((*nitr).data, dfsList, cycleCheck)) return true } else if (vertices[(*nitr).data].color = vertexInfo<T>::GRAY && and cycleCheck) return true } vertices[v].color = vertexInfo<T>::BLACK dfsList.push_front(v); return false