#include bitsstdc++husing namespace std;typedef long long ll;ll nmX109109;void dfsll xll y if!Xxy return; else Xxy=0; ifx==n&&y==m coutYes; exit0; else dfsx+1y; Xx+1y=1; dfsxy+1; Xxy+1=1; dfsx
这段代码是一个使用深度优先搜索(DFS)来判断是否存在从起点(1,1)到终点(n,m)的路径的程序。程序的输入为矩阵的行数n和列数m,然后输入一个由'.'和'#'组成的矩阵,其中'.'代表可以走的路径,'#'代表障碍物。程序的输出为"Yes"表示存在路径,"No"表示不存在路径。
代码的问题是,没有处理输入的边界条件。在读取矩阵时,应该多读取一行和一列,以避免数组越界。同时,在dfs函数中,也应该先判断当前位置是否越界,再判断是否为障碍物。修正后的代码如下:
#include <bits/stdc++.h>
using 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;
}
这样修正后的代码应该可以正确运行并给出正确的结果
原文地址: http://www.cveoy.top/t/topic/ibEQ 著作权归作者所有。请勿转载和采集!