Skip to content

Instantly share code, notes, and snippets.

@woodywang
Created July 31, 2014 12:50
Show Gist options
  • Save woodywang/72ad1ac79d42b7c8eb77 to your computer and use it in GitHub Desktop.
Save woodywang/72ad1ac79d42b7c8eb77 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Mouse {
/**
* @param args
*/
private boolean found = false;
public int si, sj, ei, ej;
public boolean vist(char[][] bear, int i, int j, int R, int C){
if (this.found) {
return true;
}
if (bear[i][j] == 'u') {
return this.found;
}
bear[i][j] = 'u';
if(i == ei && j == ej){
this.found = true;
}
if(j < C - 1 && bear[i][j+1] == '-')
vist(bear, i, j+1, R, C);
if(i < R - 1 && bear[i+1][j] == '-')
vist(bear, i+1, j, R, C);
if((j -1) >= 0 && bear[i][j-1] == '-')
vist(bear, i, j-1, R, C);
if((i - 1)>=0 && bear[i-1][j] == '-')
vist(bear, i-1, j, R, C);
return this.found;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int R, C;
R = Integer.parseInt(scanner.nextLine());
C = Integer.parseInt(scanner.nextLine());
char[][] bear = new char[R][C];
int i = 0;
Mouse m = new Mouse();
for (int k = 0; k < R; k++) {
String s = scanner.next();
char[] ss = s.toCharArray();
for(int j = 0; j < C; j++){
bear[i][j] = ss[j];
if(bear[i][j] == 'B'){
m.si = i;
m.sj = j;
}
if(bear[i][j] == 'H'){
m.ei = i;
m.ej = j;
}
}
i++;
}
if(m.vist(bear, m.si, m.sj, R, C))
System.out.println("Y");
else
System.out.println("N");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment