ProgramAlgTrain/20240919/CSP常考算法模板/DFS.cpp

62 lines
1.1 KiB
C++

#include <bits/stdc++.h>
using namespace std;
int n,m,p,q,minn=INT_MAX;
int a[51][51];
bool book[51][51];
// 方向数组
int dir[4][2]={ {0,1} , //向右走
{1,0} , //向下走
{0,-1}, //向左走
{-1,0} } ;//向上走
void dfs(int x,int y,int step){
// 判断是否到终点
if(x==p && y==q){
minn = min(minn, step);
return;
}
// 剪枝
if(step>=minn) // 如果未到终点步数就已经达到或超过最小值,就返回。
return;
// 枚举每一个方向
for(int i=0; i<=3; i++){
//计算下一个点的坐标
int nx=x+dir[i][0];
int ny=y+dir[i][1];
// 判断是否越界
if(nx<1 || nx>n || ny<1 || ny>m)
continue;
if(a[nx][ny]==0 && !book[nx][ny]){
book[nx][ny]=true;
dfs(nx,ny,step+1);
book[nx][ny]=false; // 回溯
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int i ,j,startx,starty;
cin>>n>>m;
//读入迷宫
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
cin>>a[i][j];
cin>>startx>>starty>>p>>q;
book[startx][starty]=true;
dfs(startx,starty,0);
cout<<minn<<endl;
return 0;
}