输入:
5 4
1 1
4 3
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
输出:
7
*
``
深度优先搜索可以形象化为“打破砂锅问到底”,可以理解为电磁波,信号是一束一束的进行发射,即访问了当前节点后我进而访问该节点的下一个节点,直到问题结束。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<cmath>
using namespace std;
int a[51][51];//用于输入地图
int book[51][51];//用于标记点是否走过
int sx,sy,n,m,p,q,mini=9999999,step=0;
void dfs(int x,int y,int step){
int next[4][2]={//下一步,顺序为顺时针
{0,1},
{1,0},
{0,-1},
{-1,0}
} ;
int tx,ty;
if(x==p&&y==q){ //找到了小哈
if(mini>step)
mini=step;
return;
}
for(int k=0;k<=3;k++){
tx=x+next[k][0];
ty=y+next[k][1];
if(tx<1||tx>n||ty<1||ty>m)//判断是否超过地图界限
continue;
if(a[tx][ty]==0&&book[tx][ty]==0){//如果该点不是墙并且未走过
book[tx][ty]=1;//做上标记
dfs(tx,ty,step+1);//递归继续下一步
book[tx][ty]=0;//下一步结束,取消标记
}
}
return;
}
int main(){
cin>>n>>m;
cin>>sx>>sy;
cin>>p>>q;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
book[sx][sy]=1;
dfs(sx,sy,0);
cout<<mini<<endl;
}