Undirected Graph Adjacency List Implementation public class Graph
Undirected Graph: Adjacency List Implementation public class Graph { private int V; private Node[] adj; private int[] degree; private static class Node { int vertex; Node next; Node(int v, Node next) { this. vertex = v; this. next = next; } } public Graph(int V) { this. V = V; adj = new Node[V]; degree = new int[V]; } node in a linked list graph on V vertices with no edges 1
Undirected Graph: Adjacency List Implementation public int V() { return V; } public void add. Edge(int v, int w) { adj[v] = new Node(w, adj[v]); adj[w] = new Node(v, adj[w]); degree[v]++; degree[w]++; } # vertices add w to v's adjacency list add v to w's adjacency list public int[] neighbors(int v) { int[] neighbors = new int[degree[v]]; int i = 0; for (Node x = adj[v]; x != null; x = x. next) neighbors[i++] = x. vertex; return neighbors; } return list of neighbors of v as an array 2
Connected Components Connected components of a graph G. How many connected components? For each vertex, give id number corresponding to component. n n public class DFSearcher { private static int UNMARKED = -1; private int[] cc; private int components; public DFSearcher(Graph G) { // next slide } public int component(int v) { return cc[v]; } public int components() { return components; } 3
Connected Components: Depth first Search public DFSearcher(Graph G) { components = 0; cc = new int[G. V()]; for (int v = 0; v < G. V(); v++) cc[v] = UNMARKED; for (int v = 0; v < G. V(); v++) { if (cc[v] == UNMARKED) { dfs(G, v); components++; } } } private void dfs(Graph G, int v) { cc[v] = components; int[] neighbors = G. neighbors(v); for (int i = 0; i < neighbors. length; i++) { int w = neighbors[i]; if (cc[w] == UNMARKED) dfs(G, w); } } 4
- Slides: 4