iT邦幫忙

2025 iThome 鐵人賽

0
Software Development

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

大型翻車現場&第一次講解還蠻好玩的 持續gogogo 994 well done :)

  • 分享至 

  • xImage
  •  

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

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

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

https://ithelp.ithome.com.tw/upload/images/20260329/2017794461DMzNYkW6.jpg

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

#include <vector> // both m*n
#include <queue>
using namespace std;
class Solution {
public:
    int orangesRotting(vector<vector<int>>& g) {
        int m = g.size(), n = g[0].size();
        queue<pair<int, int>> q;
        int fresh = 0;
        for(int r = 0 ; r < m ; ++r)
            for(int c = 0 ; c < n ; ++c)
                if(g[r][c]==2) q.push({r,c});
                else if(g[r][c] == 1)fresh++;
        int minutes = 0;
        int dx[4]={1, -1, 0, 0};
        int dy[4]={0, 0, 1, -1};
        while(!q.empty() && fresh > 0){
            int sz = q.size();
            while(sz--){
                auto[x, y]=q.front();q.pop();
                for(int k = 0; k < 4; ++k){
                    int nx = x + dx[k], ny = y + dy[k];
                    if(nx >= 0 && nx < m && ny >= 0 && ny <n && g[nx][ny] == 1){
                        g[nx][ny]=2;
                        fresh--;
                        q.push({nx, ny});
                    }
                } 
            }
            minutes++;
        }
        return fresh==0?minutes:-1;
    }
}; 

上一篇
First time to assist mock interview and push me memorized the problem 200 Number of Islands 13 March
系列文
轉職仔之Data Science and ai master後的持續精進技術之路39
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言