题干网址: 点击打开链接
注意对碰到边界情况的处理,注意对impossible情况的处理,对最小步数的剪枝了解一下,了解一下......
#include <iostream>
using namespace std;
int flag = 0;
int go[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};
int a[32][32];
int minStep = 0;
int m,n; //矩阵长宽
void dfs(int x,int y,int step)
{
//cout<<"enter"<<step<<endl;
if(step >= 10 || step>minStep)
{
return;
}
for(int i=0;i<4;i++)
{
//cout<<"enter for"<<endl;
int xx = x;
int yy = y;
//cout<<xx<<" "<<yy<<" "<<endl; //0 1
while((xx>=0)&&(xx<n)&&(yy>=0)&&(yy<m))
{
//cout<<"xx yy:"<<xx<<" "<<yy<<endl;
//cout<<"enter while"<<a[xx][yy]<<" "<<step<<endl; //0 0
if(a[xx][yy] == 0 ) //空白
{
xx = xx+go[i][0];
yy = yy+go[i][1];
}
if(a[xx][yy] == 3) //目的地
{
if(step+1 < minStep)
minStep = step+1;
xx = -1;
//cout<<minStep<<endl;
}
if(a[xx][yy] == 1)
{
if(!((xx-go[i][0] == x) && (yy - go[i][1] == y))){
a[xx][yy] = 0;
dfs(xx-go[i][0],yy-go[i][1],step+1);
//退后一步再投
a[xx][yy] = 1;
}
xx = -1;
//返回操作
}
}
}
}
int main()
{
int s_x,s_y; //起始位置
int e_x,e_y; //结束位置
while(cin>>m>>n,m!=0)
{
//cin>>m>>n;
//cout<<m<<endl;
//cout<<n<<endl;
for(int i = 0;i<m;i++)
for(int j=0;j<n;j++)
{
cin>>a[j][i];
if(a[j][i] == 2)
{
s_x = j;
s_y = i;
}
if(a[j][i] == 3)
{
e_x = j;
e_y = i;
}
//cout<<a[j][i]<<" ";
}
a[s_x][s_y] = 0;
minStep = 11;
dfs(s_x,s_y,0);
//输出判断
if(minStep > 10)
{
cout<<-1<<endl;
}
else
{
cout<<minStep<<endl;
}
minStep = 0;
}
return 0;
}