Description
有一个mn格的迷宫(表示有m行、n列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,输入这mn个数据和起始点、结束点(起始点和结束点都是用两个数据来描述的,分别表示这个点的行号和列号)。现在要你编程找出所有可行的道路,要求所走的路中没有重复的点,走时只能是上下左右四个方向。如果一条路都不可行,则输出相应信息(用-1表示无路)。
Input
第一行是两个数m,n(1< m, n< 15),接下来是m行n列由1和0组成的数据,最后两行是起始点和结束点。
Output
所有可行的路径,输出时按照左上右下的顺序。描述一个点时用(x,y)的形式,除开始点外,其他的都要用“->”表示。如果没有一条可行的路则输出-1。
Sample
Input
5 4
1 1 0 0
1 1 1 1
0 1 1 0
1 1 0 1
1 1 1 1
1 1
5 4
Output
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
代码如下:
import java.util.Scanner;
public class Main {
static int[][] a;
static int count = 0;
static int b2, e2, m, n;
static int[] b = new int[100];
static int[][] dir = {{0,-1},{-1,0},{0,1},{1,0}}; //左, 下,右,上
static int flag = 0;
public static void dfs(int x, int y, int count) {
//到了终点
if(x==b2 && y==e2) {
flag = 1;
for(int i=0; i<count; i+=2) {
System.out.print("("+b[i]+","+b[i+1]+")->");
}
System.out.println("("+b2+","+e2+")");
return;
}
//边界条件
if(x == 0||x == m+1 || y == n+1||y == 0 || a[x][y] == 0) return;
//四个方向各走一次
for(int i=0; i<4; i++) {
a[x][y] = 0; //将遍历方向置0
b[count] = x;
b[count+1] = y;
dfs(x+dir[i][0], y+dir[i][1], count+2);
a[x][y] = 1; //恢复
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
m = scan.nextInt();
n = scan.nextInt();
a = new int[m+1][n+1];
for(int i=1; i<=m; i++) {
for(int j=1; j<=n; j++) {
a[i][j] = scan.nextInt();
}
}
int b1, e1;
b1 = scan.nextInt();
e1 = scan.nextInt();
b2 = scan.nextInt();
e2 = scan.nextInt();
dfs(b1, e1, 0);
if(flag == 0) System.out.println("-1");
}
scan.close();
}
}