zoukankan      html  css  js  c++  java
  • 695. Max Area of Island

    You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    The area of an island is the number of cells with a value 1 in the island.

    Return the maximum area of an island in grid. If there is no island, return 0.

    Example 1:

    Input: grid = [[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]]
    Output: 6
    Explanation: The answer is not 11, because the island must be connected 4-directionally.
    

    Example 2:

    Input: grid = [[0,0,0,0,0,0,0,0]]
    Output: 0
    

    Constraints:

    • m == grid.length
    • n == grid[i].length
    • 1 <= m, n <= 50
    • grid[i][j] is either 0 or 1.
    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int res = 0;
            for(int i = 0; i < grid.length; i++) {
                for(int j = 0; j < grid[0].length; j++) {
                    if(grid[i][j] == 1) {
                        res = Math.max(res, dfs(i, j, grid));
                    }
                }
            }
            return res;
        }
        
        public int dfs(int i, int j, int[][] grid) {
            if(i >= grid.length || i < 0 || j < 0 || j >= grid[0].length || grid[i][j] == 0) return 0;
    
            grid[i][j] = 0;
            return 1 + dfs(i, j - 1, grid)+
            dfs(i-1, j, grid)+
            dfs(i+1, j, grid)+
            dfs(i, j+1, grid);
        }
    }

    similar to #200.

  • 相关阅读:
    form组件进阶_django
    form组件_django
    django的数据库ORM进阶操作
    内网安装python模块_python
    Redhat7.4安装oracle11.2.0.4版本数据库遇见的问题_oracle
    Redis基础数据类型与对象
    SpringIOC容器——ApplicationContext和BeanFactory
    AQS源码解析
    Java内存模型(一)
    面试准备笔记
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/15010292.html
Copyright © 2011-2022 走看看