public class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
public class MazeDFS{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int m = sc.nextInt();
int n = sc.nextInt();
int[][] map = new int[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j< n; j++){
map[i][j]= sc.nextInt();
}
}
Stack<Node> stack = new Stack<Node>();
int[][] visited = new int[m][n];
int[][] dir = {{1,0},{0,1}};
Node start = new Node(0,0);
Node end = new Node(m-1,n-1);
visited[start.x][start.y] = 1;
stack.push(start);
while(!stack.isEmpty()){
Node local = stack.peek();
if(local.x == end.x && local.y == end.y){
break;
}
flag = false;
for(int i = 0; i < 2; i++){
Node next = new Node(local.x + dir[i][0], local.y + dir[i][1]);
if(next.x >=0 && next.x < m
&& next.y >= 0 && next.y < n
&& map[next.x][next.y] == 0
&& visited[next.x][next.y] == 0){
stack.push(next);
flag = true;
visited[next.x][next.y]= 1;
break;
}
}
if(flag == true) continue;
stack.pop();
}
Iterator iter = stack.iterator();
while(iter.hasNext()){
Node it = iter.next();
System.out.println("(" + it.x + "," + it.y +")");
}
}
}
}
输入:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出:
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)