C++ 深度优先搜索 (DFS) 算法解决迷宫问题:边界条件处理
#include <bits/stdc++.h>\nusing namespace std;
typedef long long ll;
ll n,m,X[109][109];
void dfs(ll x,ll y){
if(x < 1 || x > n || y < 1 || y > m || !X[x][y]) return;
else X[x][y] = 0;
if(x == n && y == m){
cout << "Yes";
exit(0);
}
else{
dfs(x+1,y);
X[x+1][y] = 1;
dfs(x,y+1);
X[x][y+1] = 1;
dfs(x-1,y);
X[x-1][y] = 1;
dfs(x,y-1);
X[x][y-1] = 1;
}
}
int main() {
cin >> n >> m;
char a;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> a;
X[i][j] = (a == '.' ? 1 : 0);
}
}
dfs(1,1);
cout << "No";
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pUlF 著作权归作者所有。请勿转载和采集!