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;
    }
};
相关推荐
清泓y1 小时前
RAG 技术
算法·ai
阿慧今天瘦了嘛1 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法
网站优化(SEO)专家2 小时前
SEO核心算法拆解:网站排名快速提升的武林秘籍!
算法·搜索引擎·网站排名·核心算法
惊讶的猫2 小时前
CLGSI
人工智能·算法·机器学习
ysa0510303 小时前
【板子】二分答案(最大最小?)
c++·笔记·算法·板子
科技之门3 小时前
百公里管网漏损分级定位实战方案2026
前端·人工智能·算法
木木子224 小时前
# 猜数字游戏 — HarmonyOS交互逻辑与随机算法实现
算法·游戏·华为·交互·harmonyos
stolentime4 小时前
SP8549 MAIN75 - BST again题解
c++·算法·二叉树·深度优先·图论·记忆化搜索·组合数学
stolentime5 小时前
AT_pakencamp_2020_day1_k Gcd of Sum题解
c++·算法
2601_956121975 小时前
map_计蒜客T1271 完美K倍子数组
c++·算法