题解 | 迷宫问题
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include <iostream>
#include<bits/stdc++.h>
#include <vector>
using namespace std;
int main() {
int h, w;cin>>h>>w;
vector<vector<int>>grid(h,vector<int>(w));
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>grid[i][j];
}
}
int orient[4][2]={1,0,0,1,-1,0,0,-1};
queue<int>que;
int x,y;
que.push(0);que.push(0);
grid[0][0]=1;
vector<vector<int>>fromX(h,vector<int>(w,-1));
vector<vector<int>>fromY(h,vector<int>(w,-1));
fromX[0][0]=0;fromY[0][0]=0;
while(!que.empty()){
// cout<<"进入";
x=que.front();que.pop();
y=que.front();que.pop();
// cout<<"x="<<x<<",y="<<y<<endl;
if(x==h-1&&y==w-1){break;}
for(int i=0;i<4;i++){
int x1=x+orient[i][0];
int y1=y+orient[i][1];
// cout<<"x1="<<x1<<",y1="<<y1<<endl;
if(x1>=0&&x1<h&&y1>=0&&y1<w){
if(grid[x1][y1]==0){
que.push(x1);
que.push(y1);
grid[x1][y1]=1;
fromX[x1][y1]=x;
fromY[x1][y1]=y;
}
}
}
}
stack<int>stk;
x=h-1,y=w-1;
while (!(x==0&&y==0)) {
stk.push(x);stk.push(y);
int x1=fromX[x][y];
int y1=fromY[x][y];
x=x1;y=y1;
// cout<<"x="<<x<<",y="<<y<<endl;
}
stk.push(0);stk.push(0);
while (!stk.empty()) {
y=stk.top();stk.pop();
x=stk.top();stk.pop();
cout<<"("<<x<<","<<y<<")"<<endl;
}
}
// 64 位输出请用 printf("%lld")
广搜作法:我说真的这题就不该用广搜。啊,不对,最短路径必须用广搜。
深搜法:
#include <iostream>
#include<bits/stdc++.h>
#include <vector>
using namespace std;
int orient[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
vector<pair<int, int>>path;
void dfs(vector<vector<int>>& grid, int x, int y) {
path.push_back({x, y});
if (x == grid.size() - 1 && y == grid[0].size() - 1) {
for (auto it : path) {
cout << "(" << it.first << "," << it.second << ")" << endl;
}
// cout << "找到了";
return;
}
for (int i = 0; i < 4; i++) {
int x1 = x + orient[i][0];
int y1 = y + orient[i][1];
// cout<<"x1="<<x1<<",y1="<<y1<<endl;
if (x1 >= 0 && x1 < grid.size() && y1 >= 0 && y1 < grid[0].size()) {
if (grid[x1][y1] == 0) {
grid[x1][y1] = 1;
dfs(grid, x1, y1);
// grid[x1][y1] = 0;
}
}
}
path.pop_back();//注意回溯
}
int main() {
int h, w;
cin >> h >> w;
vector<vector<int>>grid(h, vector<int>(w));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> grid[i][j];
}
}
queue<pair<int, int>>que;
int x, y;
que.push({0, 0});
grid[0][0] = 1;
path.clear();
dfs(grid, 0, 0);
}
// 64 位输出请用 printf("%lld")
