zoukankan      html  css  js  c++  java
  • 463. Island Perimeter Add to List

    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.

    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:
    

    //

    两个循环上下左右都检查一遍

    第一次思考的时候想的是只检查右下,但是发现会重复,

    然后又加了左上的判断。

    后来仔细想想只对左上判断也是可以的。

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int sum=0;
            for(int i=0;i<grid.size();i++)
                for(int j=0;j<grid[0].size();j++){
                    if(grid[i][j]==1){
                        sum+=4;
                        grid[i][j]=2;
                        if(i-1>=0&&grid[i-1][j]==2)
                            sum--;
                        if(j-1>=0&&grid[i][j-1]==2)
                            sum--;
                        if((i+1<grid.size())&&grid[i+1][j]==1)
                            sum--;
                        if(j+1<grid[0].size()&&grid[i][j+1]==1)
                            sum--;
                    }
                }
            return sum;
        }
    };
  • 相关阅读:
    Android 开发 学习网站
    Ping 命令详解
    总结 Mac OS 安装 mysql 遇到的各种坑
    转载:django model orM 用字典作为参数,保存数据
    Django模型层Meta内部类详解 [引]
    Django 框架下的bootcamp搭建 ---第二篇笔
    Django 框架下的Blog 搭建 ---第一篇笔记
    Flask +SQL 操作
    python 开源项目大全
    cent OS 安装python
  • 原文地址:https://www.cnblogs.com/hutonm/p/6236571.html
Copyright © 2011-2022 走看看