走迷宫
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)
#include <stdio.h>
#include <string.h>
int a[30][30];
int b[100];
int dir[4][2]={{0,-1},{-1,0},{0,1},{1,0}};
int c,d,f;
void s(int g,int h,int k)
{
int i;
if(g==c&&h==d)
{
f=1;
for(i=0;i<k;i+=2)
{
printf("(%d,%d)",b[i],b[i+1]);
if(i<k)
printf("->");
}
printf("(%d,%d)\n",c,d);
return;
}
if(!a[g][h])
return;
for(i=0;i<4;i++)
{
a[g][h]=0;
b[k]=g;
b[k+1]=h;
s(g+dir[i][0],h+dir[i][1],k+2);
a[g][h]=1;
}
}
int main()
{
int n,m,g,h,i,j,k;
while(~scanf("%d %d",&n,&m))
{
k=f=0;
memset(b,0,sizeof(b));
memset(a,0,sizeof(a));
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
}
scanf("%d %d %d %d",&g,&h,&c,&d);
s(g,h,0);
if(!f)
printf("-1\n");
}
return 0;
}