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;
    }
};
相关推荐
民乐团扒谱机7 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T7 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
wy_hhxx8 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者8 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK10 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
风落青芜12 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z13 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah13 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
草履虫AI课14 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习