It’s about the Is It a Snake
problem asked in the contest.
My Code:
public static void dfs(int i, int x ){
while(true){
V[x][i]=true;
int in = x^1;
if(!V[in][i] && A[in].charAt(i)=='#') x=in;
else if(i+1<n && A[x].charAt(i+1)=='#') i++;
else break;
}
}
Calling this function and checking if path exist.
for(int i=0;i<A.length;i++){
if(A[0].charAt(i)=='#'){
V = new boolean[2][n];
dfs(i,0);
boolean Good = true;
for(int j=0;j<n;j++)
if(A[0].charAt(j)=='#' && !V[0][j]) Good=false;
else if(A[1].charAt(j)=='#' && !V[1][j]) Good=false;
if(Good) G=true;
if(A[1].charAt(i)!='#') break;
V = new boolean[2][n];
dfs(i,1);
Good = true;
for(int j=0;j<n;j++)
if(A[0].charAt(j)=='#' && !V[0][j]) Good=false;
else if(A[1].charAt(j)=='#' && !V[1][j]) Good=false;
if(Good) G=true;
break;
} else if(A[1].charAt(i)=='#'){
V = new boolean[2][n];
dfs(i,1);
boolean Good = true;
for(int j=0;j<n;j++)
if(A[0].charAt(j)=='#' && !V[0][j]) Good=false;
else if(A[1].charAt(j)=='#' && !V[1][j]) Good=false;
if(Good) G=true;
break;
}
}
System.out.println(G?"yes":"no");
What’s wrong here ?