Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 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)

Similar presentations


Presentation on theme: "1 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)"— Presentation transcript:

1 1 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]; } Undirected Graph: Adjacency List Implementation node in a linked list graph on V vertices with no edges

2 2 public int V() { return V; } public void addEdge(int v, int w) { adj[v] = new Node(w, adj[v]); adj[w] = new Node(v, adj[w]); degree[v]++; degree[w]++; } 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; } Undirected Graph: Adjacency List Implementation # vertices add w to v's adjacency list add v to w's adjacency list return list of neighbors of v as an array

3 3 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; } Connected Components Connected components of a graph G. n How many connected components? n For each vertex, give id number corresponding to component.

4 4 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); } Connected Components: Depth first Search


Download ppt "1 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)"

Similar presentations


Ads by Google