当前位置:网站首页>网格(Grid)

网格(Grid)

2022-07-07 21:50:00 Yake1965

463. 岛屿的周长

class Solution {
    
    int[] a = {
    0, 1, 0, -1}, b = {
    1, 0, -1, 0};
    public int islandPerimeter(int[][] grid) {
    
        int n = grid.length, m = grid[0].length, ans = 0;
        for (int i = 0; i < n; ++i) {
    
            for (int j = 0; j < m; ++j) {
    
                if (grid[i][j] == 0) continue;               
                for (int k = 0; k < 4; k++) {
    
                    int x = i + a[k], y = j + b[k];
                    if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0) ans += 1; 
                }
            }
        }
        return ans;
    }
}

200. 岛屿数量

class Solution {
    
    int m, n;
    public int numIslands(char[][] grid) {
    
        m = grid.length;
        n = grid[0].length;
        int ans = 0;
        for (int i = 0; i < m; i++) {
    
            for (int j = 0; j < n; j++) {
    
                if (grid[i][j] == '1') {
    
                    ans++;
                    dfs(grid, i, j);
                }
            }
        }
        return ans;
    }
    void dfs(char[][] grid, int i, int j) {
    
        if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == '0') return;
        grid[i][j] = '0';
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }
}

1905. 统计子岛屿

695. 岛屿的最大面积

1254. 统计封闭岛屿的数目

827. 最大人工岛

1568. 使陆地分离的最少天数

417. 太平洋大西洋水流问题

剑指 Offer II 105. 岛屿的最大面积

原网站

版权声明
本文为[Yake1965]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43955170/article/details/125654909