class Node{
int x;
int y;
int prex; //上一个结点的坐标,为方便计算路径
int prey;
}
public class Maze{
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();
}
}
//为BFS做些初始化
Queue<Node> queue = new LinkedList<Node>();
ArrayList<Node> arrayList = new ArrayList<Node>();
int[][] visited = new int[m][n];
int[][] dir = {{1,0},{0,1}};
//起始点为(0,0),终点为(m-1,n-1),即从左上走到右下,所以dir只有2个方向
queue.offer(new Node(0,0));
visited[0][0] = 1;
while(!queue.isEmpty()){
Node local = queue.remove();
arrayList.add(local);
for(int i=0; i< dir.length; 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){
queue.offer(next);
visited[next.x][next.y] = 1;
next.prex = local.x;
next.prey = local.y;
}
}
//接下来就是输出路径了
Stack<Integer> stack = new Stack<Integer>();
//出口的上一个结点
int px = arrayList.get(arrayList.size()-1).prex;
int py = arrayList.get(arrayList.size()-1).prey;
while(true){
if(px == 0 && py == 0){
break;
}
for(int i = 0; i < arrayList.size(); i++){
if(arrayList.get(i).prex==px && arrayList.get(i).prey==py){
px = arrayList.get(i).prex;
py = arrayList.get(i).prey;
stack.push(i);
break;
}
}
}
stack.push(0);
while(!stack.isEmpty()){
System.out.println("("+arrayList.get(stack.peer()).x+","+arrayList.get(stack.peer()).y+")");
stack.pop();
}
}
}
sc.close();
}
}
输入例子:
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)