求最少步数
输入:
第一行有两个数n,m。n代表迷宫的行,m代表迷宫的列。
接下来的n行m列为迷宫,0代表空地,1代表障碍物。
最后一行4个数,前面两个为迷宫的入口的x和y坐标。后两个为小哈的x坐标和y坐标。
例如输入:
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
#include<iostream>
using namespace std;
int p,q,n,m;
int total=999999;
int used[51][51],state[51][51];
void dfs(int x,int y,int step)
{
int tx,ty;
int next[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
if(tx==p&&ty==q)
{
if(step<total)
total=step;
return;
}
for(int k=0;k<4;k++)
{
tx=x+next[k][0];
ty=y+next[k][1];
if(tx<0||tx>(n-1)||ty<0||ty>(m-1)) continue;
if(state[tx][ty]==0&&used[tx][ty]==0)
{
used[tx][ty]=1;
dfs(tx,ty,step);
used[tx][ty]=0;
}
}
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>state[i][j];
int startx,starty;
cin>>startx>>starty;
cin>>p>>q;
used[startx][starty]=1;
dfs(startx,starty,0);
cout<<total<<endl;
return 0;
}