LeetCode

LeetCode 695. 岛屿的最大面积

2020-03-16  本文已影响0人  桐桑入梦

给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。

找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)

示例 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]

对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。

示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0

注意:
给定的矩阵grid 的长度和宽度都不超过 50。

class Solution {
    private final int[] dx = new int[]{0, 0, 1, -1};
    private final int[] dy = new int[]{1, -1, 0, 0};
    private int m, n;
    private class Point{
        int x, y;
        Point(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    public int maxAreaOfIsland(int[][] grid) {
        int maxArea = 0;
        m = grid.length;
        n = grid[0].length;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 1){
                    int area = bfs( i, j, grid );
                    maxArea = Math.max(maxArea, area);
                }
            }
        }
        return maxArea;
    }
    private int bfs( int x, int y, int[][] grid){
        int res = 1;
        Queue<Point> queue = new LinkedList<Point>();
        queue.add(new Point(x, y));
        grid[x][y] = 0;
        while( !queue.isEmpty() ){
            Point point = queue.poll();
            for( int k = 0; k < 4; k++ ){
                int nx = point.x + dx[k];
                int ny = point.y + dy[k];
                if(nx >= 0 && nx < m && ny >=0 && ny < n && grid[nx][ny] == 1){
                    queue.add(new Point(nx, ny));
                    grid[nx][ny] = 0;
                    res += 1;
                    //System.out.println(x + ", " + y);
                }
            }
        }
        return res;
    }
} 

使用dfs更快一些

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        int max = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == 1){
                    max = Math.max (dfs(grid, i, j), max);
                }
            }
        }
        return max;
    }
    int dfs(int[][] grid, int i, int j){
        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0){
            return 0;
        }
        grid[i][j] = 0;
        int count = 1;
        count += dfs(grid, i+1, j);
        count += dfs(grid, i-1, j);
        count += dfs(grid, i, j+1);
        count += dfs(grid, i, j-1);
        return count;
    }
}
上一篇下一篇

猜你喜欢

热点阅读