This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package graph; | |
import java.util.Iterator; | |
import java.util.LinkedList; | |
/** | |
* Created by panded4 | |
*/ | |
public class DFS { | |
LinkedList<Integer> adj[]; | |
private int v; | |
public DFS(int v) { | |
this.v = v; | |
adj = new LinkedList[v]; | |
for (int i = 0; i < v; i++) { | |
adj[i] = new LinkedList<>(); | |
} | |
} | |
public static void main(String[] args) { | |
DFS g = new DFS(4); | |
g.addEdge(0, 1); | |
g.addEdge(0, 2); | |
g.addEdge(1, 2); | |
g.addEdge(2, 0); | |
g.addEdge(2, 3); | |
g.addEdge(3, 3); | |
System.out.println("Following is Depth First Traversal " + | |
"(starting from vertex 2)"); | |
g.callDFS(2); | |
} | |
private void callDFS(int i) { | |
boolean[] visited = new boolean[v]; | |
dfsUtil(i, visited); | |
} | |
private void dfsUtil(int i, boolean[] visited) { | |
visited[i] = true; | |
System.out.print(i + " "); | |
Iterator<Integer> iterator = adj[i].listIterator(); | |
while (iterator.hasNext()) { | |
int n = iterator.next(); | |
if (!visited[n]) | |
dfsUtil(n, visited); | |
} | |
} | |
private void addEdge(int i, int w) { | |
adj[i].add(w); | |
} | |
} |
No comments:
Post a Comment