According to above picture DFS should be: 0 1 3 5 4 2
but it's returning 0 1 3 5 2
(This is happening only for one case. What I am doing wrong here?)
code:
import java.util.Stack;
public class DFSDetectCycleSelf {
static int arr[][] = {
{ 0, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 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 }
//working fine for static int arr[][]={{0,1,1,0,0,0},
// {0,0,0,1,1,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}};
static Stack<Integer> stack;
DFSDetectCycleSelf(){
stack = new Stack<Integer>();
}
public static void main(String[] args){
DFSDetectCycleSelf df = new DFSDetectCycleSelf();
PrintDFS();
}
public static void PrintDFS(){
int source = 0;
int numberOfNodes = arr[source].length;
int [] visited = new int[numberOfNodes];
int v;
stack.push(source);
while (!stack.isEmpty()){
v = stack.pop();
if(visited[v]==0) {
visited[v] = 1;
System.out.println(v);
}
for(int i=0;i<numberOfNodes;i++){
if(arr[v][i]==1 && visited[i]==0){
stack.push(v);
System.out.println(i);
visited[i]=1;
v = i;
}
}
}
}
}