You are on page 1of 2

package second_project;

import java.util.*;
//Implemetation of DFS traversal using adjacency
matrix.
//it gives preorder raversal of the graph.
public class Dfs_traversal {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of
vertices");
int v = scan.nextInt();
int[][] adj = new int[v][v];
System.out.println("Enter the adj matrix");
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
adj[i][j] = scan.nextInt();
}
}
System.out.println("Traversal starts from
vertex 0:");
boolean[] vis = new boolean[v];
for (int i = 0; i < v; i++) {
if (!vis[i])
dfs(i, v, adj, vis);
}
scan.close();
}
public static void dfs(int s, int v, int[][]
adj, boolean[] vis) {
vis[s] = true;
System.out.print(s + " "); // Print the
current vertex
for (int i = 0; i < v; i++) {
if (adj[s][i] == 1 && !vis[i]) {
dfs(i, v, adj, vis);
}
}
}
}

You might also like