zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    和菜鸟一起学android4.0.3源码之硬件gps简单移植
    Android学习笔记(三一):线程:Message和Runnable
    Android Runnable 运行在那个线程
    Android 的消息队列模型
    iOS开发UI篇—iOS开发中三种简单的动画设置
    ios开发UI篇—在ImageView中添加按钮以及Tag的参数说明
    ios开发UI篇—Kvc简单介绍
    iOS开发UI篇—从代码的逐步优化看MVC
    iOS开发UI篇—字典转模型
    iOS开发UI篇—九宫格坐标计算
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8919473.html
Copyright © 2011-2022 走看看