dfs 深度优先搜索
DFS 算法
#include <iostream>
using namespace std;
int n,m,p,q,nmin = 9999;
int a[51][51],book[51][51];
void dfs(int x,int y,int step){//深度优先搜索
int next[4][2] = {{1,0},{0,1},{0,-1},{-1,0}};
int tx,ty;
if(x == p && y == q){
if(step < nmin){
nmin = step;
}
return;
}
//计算下一个目标的坐标
for(int k=0;k<=3;k++){
tx = x + next[k][0];
ty = y + next[k][1];
if(tx > n || ty >m || tx < 1 || ty <1)
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(){
int startx,starty;
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
cin>>startx>>starty>>p>>q;
book[startx][starty] = 1;
dfs(startx,starty,0);
cout<<nmin<<endl;
return 0;
}