LeetCode第 490 题:迷宫(C++)

490. 迷宫 - 力扣(LeetCode)

class Solution {
public:
    vector<vector<bool>> visited;
    vector<vector<int>> dirs = {{0,1}, {0,-1},{1,0},{-1,0}};
    bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
        int n = maze.size(), m = maze[0].size();
        visited = vector<vector<bool>>(n, vector<bool>(m, false));
        queue<pair<int, int>>   q;
        q.push({start[0], start[1]});
        visited[start[0]][start[1]] = true;
        while(!q.empty()){
            auto t = q.front();
            q.pop();
            if(t.first == destination[0] && t.second == destination[1]) return true;
            for(const auto &dir : dirs){
                int x = t.first, y = t.second;
                while(x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == 0){
                    x += dir[0];    y += dir[1];//一直滚知道碰壁
                }
                x -= dir[0];    y -= dir[1];
                if(!visited[x][y]){
                    q.push({x, y});
                    visited[x][y] = true;//标记停下来的点
                }
            }
        }
        return false;
    }
};

自己在ide上面写一写

bfs,四个方向都考虑就可以了,唯一值得注意的点是每一次碰到墙之后才会停止,所以要使用while循环来求解滚动之后的位置

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int MAXN = 110;
int maze[MAXN][MAXN]; 
int start[2];
int destination[2];

bool bfs(vector<vector<bool>> &visited, vector<vector<int>> &dirs, int n, int m){
    queue<pair<int, int>> q;
    q.push({start[0], start[1]});
    visited[start[0]][start[1]] = true;
    while(!q.empty()){
        auto t = q.front();
        q.pop();
        if(t.first == destination[0] && t.second == destination[1]) return true;

        for(const auto &dir : dirs){//遍历每个方向
            int x = t.first, y = t.second;
            while(x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == 0){
                x += dir[0]; y += dir[1];
            } 
            x -= dir[0]; y -= dir[1];//上面加过了
            if(!visited[x][y]){
                visited[x][y] = true;//标记停下来的点
                q.push({x, y});
            }
        }
    }
}

int main(){
    int n, m;
    cin >> n >> m;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j)
            cin >> maze[i][j];
    }
    cin >> start[0] >> start[1];
    cin >> destination[0] >> destination[1];

    vector<vector<bool>> visited(n, vector<bool>(m, false));
    vector<vector<int>> dirs = {{0,1}, {0,-1},{1,0},{-1,0}};
    bool flag = bfs(visited, dirs, n, m);
    if(flag) cout << 1 << endl;
    else cout << 0 << endl;

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值