463. Island Perimeter岛屿周长

[抄题]:

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

Example:

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

Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

+--+     +--+                   +--+--+
|  |  +  |  |          ->       |     |
+--+     +--+                   +--+--+
4 + 4 - ? = 6  -> ? = 2 

[一刷]:

  1. “连续统计”的题往往有准入门槛。必须第一个数符合条件,才能做后续的统计。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

连续统计,对以第一个数有准入条件

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

733. Flood Fill 就是DFS把

 [代码风格] :

class Solution {
    public int islandPerimeter(int[][] grid) {
        //cc
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        //ini
        int island = 0, neighbor = 0;
        
        //for loop
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                //basic access
                if (grid[i][j] == 1) {
                    island++;
                    if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbor++;
                    if (j < grid[0].length - 1 && grid[i][j + 1] == 1) neighbor++;
                }
            }
        }
        
        //return res;
        return island * 4 - neighbor * 2;
    }
}
View Code

 

posted @ 2018-04-23 15:35  苗妙苗  阅读(108)  评论(0编辑  收藏  举报