#include<iostream>
using namespace std;
const int N=25;
char maze[N][N];
int w,h;
int count;
void dfs(int x,int y,int step)
{
if (step>count) //如果当前的步数超过了最小的步数,停止
return;
int i;
for(i=x+1;i<h;i++) //往下走
{
if (i==x+1 && maze[i][y]=='1')
break;
if (maze[i][y]=='3') //保证获取最小的步数
{
if(step<count)
count=step;
}
if (maze[i][y]=='1')
{
maze[i][y]='0';
dfs(i-1,y,step+1);
maze[i][y]='1';
break;
}
}
for(i=x-1;i>=0;i--) //往上走
{
if (i==x-1 && maze[i][y]=='1')
break;
if (maze[i][y]=='3')
{
if(step<count)
count=step;
}
if (maze[i][y]=='1')
{
maze[i][y]='0';
dfs(i+1,y,step+1);
maze[i][y]='1';
break;
}
}
for(i=y-1;i>=0;i--) //往左走
{
if (i==y-1 && maze[x][i]=='1')
break;
if (maze[x][i]=='3')
{
if(step<count)
count=step;
}
if (maze[x][i]=='1')
{
maze[x][i]='0';
dfs(x,i+1,step+1);
maze[x][i]='1';
break;
}
}
for(i=y+1;i<w;i++) //往右走
{
if (i==y+1 && maze[x][i]=='1')
break;
if (maze[x][i]=='3')
{
if(step<count)
count=step;
}
if (maze[x][i]=='1')
{
maze[x][i]='0';
dfs(x,i-1,step+1);
maze[x][i]='1';
break;
}
}
}
int main()
{
int i,j,x,y;
while (cin>>w>>h)
{
count=11;
if (w==0&&h==0)
break;
for (i=0;i<h;i++)
{
for (j=0;j<w;j++)
{
cin>>maze[i][j];
if (maze[i][j]=='2')
{
x=i; y=j;
}
}
}
dfs(x,y,1);
if (count>10)
cout<<"-1"<<endl;
else
cout<<count<<endl;
}
return 0;
}
上面的代码分别编写了上下左右四个方向,可以合并起来考虑,用一个二维数组表示四个方向,代码长度可以缩短许多。
#include<iostream>
#include <cstring>
using namespace std;
const int N=25;
char maze[N][N];
int dir[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
int w,h;
int count;
void dfs(int x,int y,int step)
{
if (step>count)
return;
for (int i=0;i<4;i++)
{
int tmpx=x+dir[i][0];
int tmpy=y + dir[i][1];
if(maze[tmpx][tmpy]=='1')
continue;
while (1)
{
if (tmpx<0||tmpx==h ||tmpy<0 || tmpy==w)
break;
else
{
if (maze[tmpx][tmpy]=='3')
{
if (step<count)
count=step;
return;
}
if (maze[tmpx][tmpy]=='1')
{
maze[tmpx][tmpy]='0';
dfs(tmpx-dir[i][0],tmpy-dir[i][1],step+1);
maze[tmpx][tmpy]='1';
break;
}
}
tmpx+=dir[i][0];
tmpy+=dir[i][1];
}
}
}
int main()
{
int i,j,x,y;
while (cin>>w>>h)
{
count=11;
if (w==0&&h==0)
break;
for (i=0;i<h;i++)
{
for (j=0;j<w;j++)
{
cin>>maze[i][j];
if (maze[i][j]=='2')
{
x=i; y=j;
}
}
}
dfs(x,y,1);
if (count>10)
cout<<"-1"<<endl;
else
cout<<count<<endl;
}
return 0;
}