zoukankan      html  css  js  c++  java
  • 695. Max Area of Island最大岛屿面积

    Given a non-empty 2D array grid of 0's and 1's, 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.

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    Example 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]]
    

    Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

    Example 2:

    [[0,0,0,0,0,0,0,0]]

    Given the above grid, return 0.

    思路:

    里面:加起来,得出一个和

    外面:比较,双重for循环和所有点的和比较

    没想到的主要思路是:加一个1就消灭一个,记为0,各个击破。这是为了避免重复计算

    不是1的情况返回0

    if (grid[x][y] == 1)直接变成&,不需要嵌套

    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            //cc
            if (grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int max = 0;
            
            //每一个点逐一比较
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    max = Math.max(max, dfs(grid, i, j));
                }
            }
            
            return max;
        }
        
        //返回面积
        public int dfs(int[][] grid, int x, int y) {
            //标记
            if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 
               grid[x][y] == 1) {             
                    grid[x][y] = 0;
                    
                    return 1 + dfs(grid, x - 1, y) + dfs(grid, x + 1, y) + 
                        dfs(grid, x, y - 1) + dfs(grid, x, y + 1);          
            }
            
            return 0;
        }
    }
    View Code
  • 相关阅读:
    Redis常用配置说明
    Redis入门知识
    分布式理论基石CAP理论
    MySQL之视图
    MySQL之事务控制总结
    MySQL之标识列(自增长列)设置起始值与步长
    LeetCode 543. Diameter of Binary Tree(两节点最长路径)
    LeetCode 110. Balanced Binary Tree(平衡树)
    LeetCode 104. Maximum Depth of Binary Tree(求树的高度)
    LeetCode 328. Odd Even Linked List(链表元素按奇偶聚集)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13568697.html
Copyright © 2011-2022 走看看