MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / Graph

Class Graph

Programs/DepthFirstSearch.java:5–48  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3import java.util.*;
4
5class Graph {
6 private LinkedList<Integer> adjLists[];
7 private boolean visited[];
8
9 // Graph creation
10 Graph(int vertices) {
11 adjLists = new LinkedList[vertices];
12 visited = new boolean[vertices];
13
14 for (int i = 0; i < vertices; i++)
15 adjLists[i] = new LinkedList<Integer>();
16 }
17
18 // Add edges
19 void addEdge(int src, int dest) {
20 adjLists[src].add(dest);
21 }
22
23 // DFS algorithm
24 void DFS(int vertex) {
25 visited[vertex] = true;
26 System.out.print(vertex + " ");
27
28 Iterator<Integer> ite = adjLists[vertex].listIterator();
29 while (ite.hasNext()) {
30 int adj = ite.next();
31 if (!visited[adj])
32 DFS(adj);
33 }
34 }
35
36 public static void main(String args[]) {
37 Graph g = new Graph(4);
38
39 g.addEdge(0, 1);
40 g.addEdge(0, 2);
41 g.addEdge(1, 2);
42 g.addEdge(2, 3);
43
44 System.out.println("Following is Depth First Traversal");
45
46 g.DFS(2);
47 }
48}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected