走迷宫
Pblem 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
Sample 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)
#include <bits/stdc++.h>
using namespace std;
struct node
{
int x, y;
} ls[1000];
int dx[] = {0,-1,0,1}, dy[] = {-1,0,1,0};
int bj[16][16], mapl[16][16];
int m, n, step, sum = 0, xz, yz;
void dfs(int x1, int y1)
{
int i;
if(x1 == xz && y1 == yz)
{
sum++;
for(i = 0; i < step; i++)
{
printf("(%d,%d)",ls[i].x,ls[i].y);
if(i < step - 1)
printf("->");
}
printf("\n");
}
else
{
int kx, ky;
for(i = 0; i < 4; i++)
{
kx = x1 + dx[i];
ky = y1 + dy[i];
if(kx >= 1 && ky >= 1 && kx <= n && ky <= m && !bj[kx][ky] && mapl[kx][ky])
{
ls[step].x = kx;
ls[step].y = ky;
step++;
bj[kx][ky] = 1;
dfs(kx,ky);
bj[kx][ky] = 0;
step--;
}
}
}
}
int main()
{
int i, j,xq,yq;
while(~scanf("%d %d",&n,&m))
{
memset(bj,0,sizeof(bj));
memset(ls,0,sizeof(ls));
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
scanf("%d",&mapl[i][j]);
scanf("%d %d %d %d",&xq,&yq,&xz,&yz);
ls[0].x = xq;
ls[0].y = yq;
sum = 0;
step = 1;
bj[xq][yq] = 1;
dfs(xq,yq);
if(sum == 0)
printf("-1\n");
}
return 0;
}