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;
    }
};
相关推荐
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧11 分钟前
C语言_数据结构总结7:顺序队列(循环队列)
c语言·开发语言·数据结构·算法·visualstudio·visual studio
LIUJH123313 分钟前
数据结构——单调栈
开发语言·数据结构·c++·算法
2301_8074492027 分钟前
字符串相乘——力扣
java·算法·leetcode
yadanuof1 小时前
leetcode hot100 图论
leetcode·深度优先·图论
---yx8989782 小时前
数字人系统源码---v10技术五大底层架构链路全局开发思路
算法·架构·数字人·数字人源码·数字人系统
xiao--xin2 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法
路飞雪吖~2 小时前
数据结构 && 常见的排序算法
数据结构·算法·排序算法
手握风云-2 小时前
Java数据结构第二十一期:解构排序算法的艺术与科学(三)
数据结构·算法·排序算法
爱吃柠檬呀2 小时前
《C陷阱与缺陷》读书笔记(一)
c语言·开发语言·算法·《c陷阱与缺陷》·编写程序
壮志凌云2 小时前
配对样本t检验
算法