| 7 | import java.util.Queue; |
| 8 | |
| 9 | class Graph{ |
| 10 | private int v ; //total number of vertices |
| 11 | private LinkedList<Integer> adj[]; //adjacency list |
| 12 | private boolean visited[]; //to keep track of the node which are visited. |
| 13 | |
| 14 | Graph(int v){ |
| 15 | this.v = v; |
| 16 | this.adj = new LinkedList[v]; |
| 17 | this.visited = new boolean[v]; |
| 18 | for(int i=0;i<this.v;i++) { |
| 19 | adj[i] = new LinkedList<Integer>(); |
| 20 | this.visited[i] = false; |
| 21 | } |
| 22 | |
| 23 | } |
| 24 | |
| 25 | |
| 26 | public void addEdge(int u,int v) { // edge from u -> v |
| 27 | this.adj[u].add(v); |
| 28 | } |
| 29 | |
| 30 | |
| 31 | public void DFS(int source) { |
| 32 | //if the node is already visited, then backtrack. |
| 33 | if(this.visited[source] == true) { |
| 34 | return; |
| 35 | } |
| 36 | //mark the source vertex as visited |
| 37 | System.out.print(source+" "); |
| 38 | this.visited[source] = true; |
| 39 | |
| 40 | //traverse through all the neighbours and backtrack if already visited. |
| 41 | LinkedList<Integer> neighbours = this.adj[source]; |
| 42 | |
| 43 | for(int next : neighbours) { |
| 44 | DFS(next); |
| 45 | } |
| 46 | |
| 47 | } |
| 48 | |
| 49 | } |
| 50 | |
| 51 | public class Main { |
| 52 | public static void main(String args[]){ |
nothing calls this directly
no outgoing calls
no test coverage detected