300 likes | 456 Vues
B Smith: Fa05: rate: 1.5. Time: 65 minutes. Graph Algorithms. Math 140. 0. 6. 2. 1. 7. 3. 4. 5. Adjacency Matrix. 0. 6. 2. 5. 6. 4. 4. 3. 1. 3. 0. 5. 2. 1. 7. 3. 4. 5. Graph Representation: Adjacency List. 0. 7. 1. 0. 2. 0. 3. 5. 4. 6. 5. 4. 6. 0. 7.
E N D
B Smith: Fa05: rate: 1.5. Time: 65 minutes Graph Algorithms Math 140
0 6 2 1 7 3 4 5 Adjacency Matrix
0 6 2 5 6 4 4 3 1 3 0 5 2 1 7 3 4 5 Graph Representation: Adjacency List 0 7 1 0 2 0 3 5 4 6 5 4 6 0 7 0
Some Graph Problems Path. Is there a path between s to t? Shortest path.What is the shortest path between two vertices? Longest path. What is the longest path between two vertices? Cycle. Is there a cycle in the graph? Euler tour. Is there a cyclic path that uses each edge exactly once? Hamilton tour. Is there a cycle that uses each vertex exactly once? Connectivity. Is there a way to connect all of the vertices? MST. What is the best way to connect all of the vertices? Biconnectivity. Is there a vertex whose removal disconnects graph? Planarity. Can you draw the graph in the plane with no crossing edges? Isomorphism. Do two adjacency matrices represent the same graph?
Graph Representation • Vertex representation • This lecture: use integers between 0 and v-1 • Real world: dictionaries to go from strings to integers
Graph API public class Graph // ADT interface { Graph(int V) //create an empty graph with V vertices Graph(int V, int E) //create a random graph with V vertices, E edges void addEdge void addEdge(int v, int w) add an edge v-w Iterable<Integer> adj(int v) return an iterator over the neighbors of v int V() return number of vertices String toString() return a string representation } Client that iterates through all edges Graph G = new Graph(V, E); StdOut.println(G); for (int v = 0; v < G.V(); v++) for (int w : G.adj(v)) // process edge v-w
Set of edges representation • Store a list of the edges (linked list or array)
Adjacency Matrix representation • Maintain a two-dimensional V x V boolean array • For each edge v-w in graph: adj[v][w] = adj[v][w] = true.
Adjacency-matrix graph representation: Java implementation public class Graph { private int V; private boolean[][] adj; public Graph(int V) { this.V = V; adj = new boolean[V][V]; } public void addEdge(int v, int w) { adj[v][w] = true; adj[w][v] = true; } public Iterable<Integer> adj(int v) { return new AdjIterator(v); } }c
Adjacency-matrix: iterator for vertex neighbors private class AdjIterator implements Iterator<Integer>, Iterable<Integer> { int v, w = 0; AdjIterator(int v) { this.v = v; } public boolean hasNext() { while (w < V) { if (adj[v][w]) return true; w++ } return false; } public int next() { if (hasNext()) return w++ ; else throw new NoSuchElementException(); } public Iterator<Integer> iterator() { return this; } }
Graph ADT • A typical client program will. . . typedef struct { int v; int w; } Edge; Edge EDGE(int, int); typedef struct graph* Graph; Graph GRAPHinit(int); // Conjure up nodes Graph GRAPHrand(int V, int E); // Randomly generate void GRAPHinsertE(Graph, Edge); // Insert an edge void GRAPHremoveE(Graph, Edge); // Remove an edge int GRAPHcc(Graph G); // Return # connected
Graph Client: class DriverExample { public static void main(String[] args) { int V = Integer.parseInt(args[0]); Graph G = new Graph(V, false); GraphIO.scanEZ(G); if (V < 20) GraphIO.show(G); Out.print(G.E() + " edges "); GraphCC Gcc = new GraphCC(G); Out.println(Gcc.count() + " components"); } }
Adjacency-List Graph ADT Implementation #include <stdlib.h> #include <time.h> #include "graph.h" /********************************************************* * Adjacency list data type. *********************************************************/ typedef struct node *link; struct node { int v; // destination node of edge link next; // next element in adjacency list }; /********************************************************* * Graph data type. *********************************************************/ struct graph { int V; // number of vertices int E; // number of edges link *adj; // adjacency list int *cc; // connected components };
Adjacency list Graph ADT Implementation /********************************************************* * Initialize and return a new Edge. *********************************************************/ Edge EDGE(int v, int w) { Edge e; e.v = v; e.w = w; return e; } /********************************************************* * Initialize and return a new adjacency list element. *********************************************************/ link NEW(int v, link next) { link x = malloc(sizeof *x); x->v = v; x->next = next; return x; }
Adjacency list Graph ADT Implementation /********************************************************* * Initialize and return a new graph with V vertices * and no edges. *********************************************************/ Graph GRAPHinit(int V) { int v; Graph G = malloc(sizeof *G); G->V = V; G->E = 0; G->cc = malloc(V * sizeof(int)); G->adj = malloc(V * sizeof(link)); for (v = 0; v < V; v++) G->adj[v] = NULL; return G; }
Adjacency list Graph ADT Implementation /********************************************************* * Insert Edge e into Graph g. *********************************************************/ void GRAPHinsertE(Graph G, Edge e) { int v = e.v, w = e.w; G->adj[v] = NEW(w, G->adj[v]); G->adj[w] = NEW(v, G->adj[w]); G->E++; }
B Smith: not discussed Fa05, but use Sp06 /********************************************************* * Compute connected components using DFS. *********************************************************/ void dfsRcc(Graph G, int v, int id) { link t; // t is node pointer G->cc[v] = id; for (t = G->adj[v]; t != NULL; t = t->next) { if (G->cc[t->v] == -1) dfsRcc(G, t->v, id); } } int GRAPHcc(Graph G) { int v, id = 0; for (v = 0; v < G->V; v++) // mark nodes unexplored G->cc[v] = -1; // -1 means not explored for (v = 0; v < G->V; v++) // if (G->cc[v] == -1) dfsRcc(G, v, id++); return id; }
A Few Graph Problems • Path. Is there a path from vertex s to vertex t? • Shortest path. What’s the shortest path b/t two vertices? • Longest path. What is the longest path between two vertices? • Cycle. Is there a cycle in the graph? • Euler tour. Is there a cyclic path that uses each edge exactly once? • Hamilton tour. is there a cycle that uses each vertex exactly once? • Connectivity. Is there a way to connect all of the vertices? • MST. What is the best way to connect all of the vertices? • Bi-connectivity. Is there a vertex whose removal disconnects the graph? • Planarity. Can you draw the graph in the plane with no crossing edges? • Isomorphism. Do tow matrices represent the same graph?
Graph Search Goal. Visit every node and edge in Graph A solution. Depth-first search • To visit a node v: • mark it as visited • recursively visit all unmarked nodes w adjacent to v • To traverse a Graph G: • initialize all nodes as unmarked • visit each unmarked node • Enables direct solution of simple graph problems • Connected components • Cycles
A B Connected Components
Connected Components Application: Minesweeper • Challenge: Implement the game of Minesweeper • Critical subroutine: • User selects a cell and program reveals how many adjacent mines • If zero, reveal all adjacent cells • If any newly revealed cells have zero adjacent mines, repeat
Breadth-First Search • Graph search. Visit all nodes and edges of graph • Depth-first search. Put unvisited nodes on a STACK • Breadth-first search. Put unvisited nodes on a QUEUE • Shortest path: what is the fewest number of edges to get from s to t? • Solution = BFS • Initialize dist[v] = ¥, dist[s] = 0. • When considering edge v-w: • if w is marked, then ignore • else, set dist[w] = dist[v] + 1, pred[w] = v, and add w to the queue
Breadth-First Search visit(Graph G, int k) { link t; QUEUEput(k); while (!QUEUEempty()) { k = QUEUEget(); mark[k] = ++id; for (t = G->adj[k]; t != z; t = t->next) if (mark[t->v] == 0) { QUEUEput(t->v); mark[t->v] = -1; } } } Put unvisited nodes on a QUEUE, not a stack