-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstTraversal.java
More file actions
45 lines (31 loc) · 977 Bytes
/
DepthFirstTraversal.java
File metadata and controls
45 lines (31 loc) · 977 Bytes
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
/*
Depth First Search (DFS) Program in java [Adjacency Matrix]
*/
package searchingAndTraversal;
import java.util.Scanner;
public class DepthFirstTraversal {
public static int[][] G = new int [10][10];
public static int[] visited = new int[10];
public static int n;
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter the number of vertices: ");
n = in.nextInt();
System.out.printf("\nEnter adjacency matrix of the graph:\n");
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
G[i][j] = in.nextInt();
//visited is initialized to zero
for (int i=0; i<n; i++)
visited[i] = 0;
DFS(0);
in.close();
}
public static void DFS(int i) {
System.out.printf("\n%d",i);
visited[i]=1;
for(int j=0; j<n; j++)
if(visited[j]==0 && G[i][j]==1)
DFS(j);
}
}