Graphs A few definitions: Vertices -a point or a place Edge - connects any two vertices Adjacency - two vertices attached by an edge Path - a sequence of edges from one vertex to another Connected Graph - at least one path from every vertex to every other vertex Cyclic Graph - can finish up where you started Directed Graph - can only travel one direction on an edge Un-Directed Graph - can travel either direction on an edge Weighted Graph - each edge holds a value (cost, time, distance) UnWeighted Graph - no value for the edges Adjacency Matrix An adjacency matrix is created by listing all vertices in rows and columns, then marking the intersecting cell for any pair that are adjacent. | | A | B | C | D | E | F | G | H | I | J | |---|---|---|---|---|---|---|---|---|---|---| | A | | x | x | x | | | | | | | |---|---|---|---|---|---|---|---|---|---|---| | B | x | | | | | x | x | | | | |---|---|---|---|---|---|---|---|---|---|---| | C | x | | | | x | | | | | | |---|---|---|---|---|---|---|---|---|---|---| | D | x | | | | | | | | | | |---|---|---|---|---|---|---|---|---|---|---| | E | | | x | | | | | | | | |---|---|---|---|---|---|---|---|---|---|---| | F | | x | | | | | x | x | x | | |---|---|---|---|---|---|---|---|---|---|---| | G | | x | | | | | | | | | |---|---|---|---|---|---|---|---|---|---|---| | H | | | | | | x | | | | | |---|---|---|---|---|---|---|---|---|---|---| | I | | | | | | x | | | | | |---|---|---|---|---|---|---|---|---|---|---| | J | | | | | | x | | | | | Adjacency List An adjaceny list is created by first listing all vertices in rows, then listing all vertices that can be directly visited from each vertex. A-> B, C, D B-> A, F, G C-> A, E D-> A E-> C F-> B, H, I, J G-> B H-> F I-> F J-> F Searching a graph Depth-First Search follow a path as far as possible, then backup to previous vertex and follow another path. Use Stack to keep track of which vertices still have paths to follow. 1. visit a vertex 2. mark it 3. push it onto a stack 4. visit an adjacent vertex if possible - loop to step 2 if not - pop the next vertex 5. When stack is empty, search is done Breadth-First Search from a vertex, visit all adjacent vertices. Use Queue to keep track of which vertices still have adjacent vertices to visit. 1. visit a vertex 2. visit all adjacent vertices, placing them in a queue 3. pop from the queue if possible - loop back to step 2 if not - done