题解 | #HJ43 迷宫问题# (dfs)
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include <bits/stdc++.h>
using namespace std;
vector<int> temp;
vector<int> ans;
vector<vector<int>> v;
vector<vector<int>> visted;
int n, m;
void dfs(vector<vector<int>>& a, int x, int y) {
if(visted[x][y]==1) return;
temp.push_back(x);
temp.push_back(y);
visted[x][y] = 1;
if (x == n - 1 && y == m - 1) {
ans = temp;
return;
}
if (x + 1 < n && a[x + 1][y] == 0) dfs(a, x + 1, y);
if (x - 1 >= 0 && a[x - 1][y] == 0) dfs(a, x - 1, y);
if (y + 1 < m && a[x][y + 1] == 0) dfs(a, x, y + 1);
if (y - 1 >= 0 && a[x][y - 1] == 0) dfs(a, x, y - 1);
temp.pop_back();
temp.pop_back();
visted[x][y] = 0;
}
int main() {
cin >> n >> m;
v.resize(n);
visted.resize(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int temp;
cin >> temp;
v[i].push_back(temp);
visted[i].push_back(0);
}
}
dfs(v, 0, 0);
for (int i = 0; i < ans.size(); i += 2) {
cout << "(" << ans[i] << "," << ans[i + 1] << ")" << endl;
}
return 0;
}
查看5道真题和解析
