-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS.java
68 lines (54 loc) · 1.69 KB
/
DFS.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Stack;
//-----------------DFS is done with Stack----------------
public class DFS {
private Stack<Integer> stack; //Stack declared for traversal of graph
//Constructor
public DFS(){
stack = new Stack<Integer>();
}
public void dfs(int[][] adjacencyMatrix, int source, int destination)
{
int noOfVertex = adjacencyMatrix[source].length -1 ;
int[] visited = new int[noOfVertex + 1]; // to hold the visited vertex
int element = source;
int i = source;
int count=0; // for counting the index
int[] traversal = new int[noOfVertex + 1] ; // to hold the visited vertex for finding shortest path
traversal[count] = element; // holds visited vertices initial value in array
count++; // saves index
System.out.println("DFS Traversal of the graph");
System.out.print(element + " "); //prints first element
visited[source] = 1;
stack.push(source); //Pushes the vertices to the stack
// prints the peek vertex and pops the vertex
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= noOfVertex)
{
if (adjacencyMatrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + " "); // prints visited elements
traversal[count] = element; // holds visited vertices in array
count++; // saves index
//continue;
}
i++;
}
stack.pop();
}
System.out.println("\nThe path is ");
for(int j=0; j<count;j++ )
{
System.out.print(traversal[j] + " ");
if (traversal[j] == destination) {
break;
}
}
}
}