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

62 lines
1.1 KiB
C++
Raw Normal View History

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