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;
    }
};
相关推荐
一念&21 小时前
每日一个C语言知识:C 错误处理
c语言·开发语言·算法
WYiQIU1 天前
高级Web前端开发工程师2025年面试题总结及参考答案【含刷题资源库】
前端·vue.js·面试·职场和发展·前端框架·reactjs·飞书
GISer_Jing1 天前
小米前端面试
前端·面试·职场和发展
丁浩6661 天前
统计学---2.描述性统计-参数估计
人工智能·算法
月明泉清1 天前
最近的面试,被打击了(随笔)
职场和发展·跳槽
sali-tec1 天前
C# 基于halcon的视觉工作流-章54-N点标定
开发语言·图像处理·算法·计算机视觉·c#
娇娇yyyyyy1 天前
C++11新特性基础知识点汇总
开发语言·c++·算法
小龙报1 天前
《赋能AI解锁Coze智能体搭建核心技能(2)--- 智能体开发基础》
人工智能·程序人生·面试·职场和发展·创业创新·学习方法·业界资讯