iT邦幫忙

2023 iThome 鐵人賽

DAY 22
0

寄信給另一個HR了~~
RRR
哪時要面試啊~~
題目要忘光了

Number of Closed Islands

Q: https://leetcode.com/problems/number-of-closed-islands/description/

class Solution {
    public int closedIsland(int[][] grid) {
        System.out.println(Arrays.deepToString(grid));
        for (int row = 0;row < grid.length;row++) {
            for (int col = 0; col < grid[row].length;col++) {
                if (row == 0 || col == 0 || row == grid.length - 1 ||  col == grid[0].length - 1) {
                    if (grid[row][col] == 0) {
                        dfs(grid, row, col);
                    }
                }
            }
        }
        int result = 0;
        for (int row = 0;row < grid.length;row++) {
            for (int col = 0; col < grid[row].length;col++) {
                if (grid[row][col] == 0) {
                    dfs(grid, row, col);
                    result++;
                }
            }
        }
        
        return result;
    }

    private void dfs(int[][] grid, int row, int col) {
        if (row < 0 || row >= grid.length || col < 0 || col >= grid[row].length) {
            return;
        }
        if (grid[row][col] == 0) {
            grid[row][col] = 2;
            dfs(grid, row - 1, col);
            dfs(grid, row + 1, col);
            dfs(grid, row, col - 1);
            dfs(grid, row, col + 1);
        }
    }
}

上一篇
09/21
下一篇
09/23
系列文
30天準備google面試30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言