iT邦幫忙

2025 iThome 鐵人賽

0
Software Development

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

First time to assist mock interview and push me memorized the problem 200 Number of Islands 13 March

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20260316/20177944vUkyq5D16m.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944XyI6KtOSCS.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/201779442Zan4iqSp2.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944wAWXgVNETB.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944UAlQr7MtgY.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944pStMCGgqkS.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944RQxvcWKZ07.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944jUc2LibUvS.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/2017794443lchGSk3S.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944aKnPzh6wiW.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944HpLODQPne3.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944LsDQO69UDY.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944gZ03IVnG7y.jpg

https://ithelp.ithome.com.tw/upload/images/20260316/20177944zaJGpAOHmk.jpg

#include <vector> // both m*n 
using namespace std;
class Solution {
public:
    int numIslands(vector<vector<char>>& g){
        int m = g.size();
        if (m == 0) return 0;
        int n = g[0].size();
        if (n == 0) return 0;
        int ans = 0;
        static const int dx[4] = {1, -1, 0, 0};
        static const int dy[4] = {0, 0, 1, -1};
        vector<int> q;
        q.reserve(m * n);
        for (int r = 0 ; r < m ; ++r) for (int c = 0 ; c < n ; ++c){
            if (g[r][c] != '1') continue;
            ++ans;
            g[r][c] = '0';
            q.clear();
            q.push_back(r * n + c);
            for (int head = 0 ; head < (int)q.size() ; ++head){
                int id = q[head];
                int x = id / n, y = id % n;
                for (int k = 0 ; k < 4 ; ++k){
                    int nx = x + dx[k], ny = y + dy[k];
                    if ((unsigned)nx >= (unsigned)m || (unsigned)ny >= (unsigned)n) continue;
                    if (g[nx][ny] == '1'){
                        g[nx][ny] = '0';
                        q.push_back(nx * n + ny);
                    }
                }
            }
        }
        return ans;
    }
};

上一篇
I have memorized 98 加油加油(0119)
系列文
轉職仔之Data Science and ai master後的持續精進技術之路38
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言