Title: Undirected Graph: Adjacency List Implementation
1Undirected 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 NodeV degree new
intV
node in a linked list
graph on V verticeswith no edges
2Undirected Graph Adjacency List Implementation
public int V() return V public void
addEdge(int v, int w) adjv new Node(w,
adjv) adjw new Node(v, adjw)
degreev degreew public int
neighbors(int v) int neighbors new
intdegreev int i 0 for (Node x
adjv x ! null x x.next)
neighborsi x.vertex return neighbors
vertices
add w to v's adjacency listadd v to w's
adjacency list
return list of neighbors of v as an array
3Connected Components
- Connected components of a graph G.
- How many connected components?
- For each vertex, give id number corresponding to
component.
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 ccv public int components()
return components
4Connected Components Depth first Search
public DFSearcher(Graph G) components
0 cc new intG.V() for (int v
0 v lt G.V() v) ccv UNMARKED for
(int v 0 v lt G.V() v) if (ccv
UNMARKED) dfs(G, v)
components private
void dfs(Graph G, int v) ccv
components int neighbors
G.neighbors(v) for (int i 0 i lt
neighbors.length i) int w
neighborsi if (ccw UNMARKED)
dfs(G, w)