Leetcode 921 Shortest Path in Binary Matrix

题意:求二维矩阵中往8个方向移动的话,从左上方到右下方移动的最短路径

https://leetcode.com/problems/shortest-path-in-binary-matrix/description/

解答:bfs易得

cpp 复制代码
class Solution {
public:
    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        int ret = 0;
        vector<vector<int>> vis(m, vector<int>(n, 0));
        if(grid[0][0] == 1 || grid[m-1][n-1] == 1) {
            return -1;
        }

        int x[] = {1, 1, 0, -1, -1, -1, 0, 1};
        int y[] = {0, 1, 1, 1,   0,-1, -1 , -1};

        queue<pair<int, int>> q;
        q.push({0,0});
        vis[0][0] = 1;
        while(q.size()) {
            int qS = q.size();
            for(int i = 0; i < qS; i++) {
                auto node = q.front();
                q.pop();
                if (node.first == m-1 && node.second == n-1) 
                    return ret+1;
                for (int k = 0 ; k < 8; k++) {
                    int dx = node.first + x[k];
                    int dy = node.second + y[k];
                    if(dx >= 0 && dx < m && dy >= 0 && dy < n && grid[dx][dy] == 0 && vis[dx][dy] == 0) {
                        q.push({dx,dy});
                        vis[dx][dy] = 1;
                    }
                }
            }
            ret += 1;
        }
        return -1;
    }
};
相关推荐
qq_423233906 分钟前
C++与Python混合编程实战
开发语言·c++·算法
TracyCoder12316 分钟前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
m0_7155753418 分钟前
分布式任务调度系统
开发语言·c++·算法
测试涛叔35 分钟前
金三银四软件测试面试题(800道)
软件测试·面试·职场和发展
naruto_lnq39 分钟前
泛型编程与STL设计思想
开发语言·c++·算法
踩坑记录1 小时前
leetcode hot100 94. 二叉树的中序遍历 easy 递归 dfs
leetcode
zxsz_com_cn1 小时前
设备预测性维护算法分类及优劣势分析,选型指南来了
算法·分类·数据挖掘
Angelina_Jolie2 小时前
一文搞懂 SCI、SSCI、CSSCI、C 刊、核心期刊:定义、作用、层级对比及投稿选择
考研·职场和发展·创业创新
m0_748708052 小时前
C++中的观察者模式实战
开发语言·c++·算法