iT邦幫忙

2025 iThome 鐵人賽

0
Software Development

轉職仔之Data Science and ai master後的持續精進技術之路系列 第 40

跟上一題很像啦 好好輸出1091要趕快出門去看排球比賽囉:)

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20260329/20177944m7DQ5BDBcs.jpg

https://ithelp.ithome.com.tw/upload/images/20260329/20177944f4Juf89ppU.jpg

https://ithelp.ithome.com.tw/upload/images/20260329/20177944UoJjNojYi6.jpg

https://ithelp.ithome.com.tw/upload/images/20260329/20177944mOG7rcprAW.png

#include <vector> // both n*n
#include <queue>
using namespace std;
class Solution {
public:
    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
        int n = (int)grid.size();
        if (grid[0][0] == 1 || grid[n-1][n-1] == 1) return -1;
        if (n == 1) return 1;
        queue<pair<int, int>> q;
        grid[0][0] = 1;
        q.push({0, 0});
        int dx[8] = {1, 1, 1, 0, 0, -1, -1, -1};
        int dy[8] = {1, 0, -1, 1, -1, 1, 0, -1};
        int dist = 1;
        while (!q.empty()) {
            int sz = (int) q.size();
            while (sz--) {
                auto [x, y] = q.front();
                q.pop();
                if (x == n - 1 && y == n - 1) return dist;
                for (int k = 0 ; k < 8 ; ++k) {
                    int nx = x + dx[k], ny = y + dy[k];
                    if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] == 0) {
                        grid[nx][ny] = 1;
                        q.push({nx, ny});
                    }
                }
            }
            dist++;
        }
        return -1;
    }
};

上一篇
大型翻車現場&第一次講解還蠻好玩的 持續gogogo 994 well done :)
系列文
轉職仔之Data Science and ai master後的持續精進技術之路40
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言