I am trying to implement DFS with recursion using the following code,
public static void dfs(int i, int[][] mat, boolean [] visited){
visited[i] = true;
System.out.print(i + "\t");
for ( int j = 0; j < visited.length; j++ ){
if ( mat[i][j] ==1 && !visited[j] ){
dfs(j, mat, visited);
}
}
}
I have a matrix and an array to track visited nodes,
int [][] arr = {
{ 0, 1, 1, 1, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
boolean [] visited = new boolean[10];
for (int i =0; i< visited.length; ){
visited[i++] = false;
}
I make the call as follows:
dfs(1, arr, visited);
This is the return
which is wrong. He must return: [1 2 7 8 9 10 3 4 5 6]
The schedule is as follows:
How can I improve my code?