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;
        }
    };
  • 相关阅读:
    the error about “no such file or directory”
    Unable to Distribute in Xcode5?
    第一次连接数据库mongodb踩的坑
    在Mac下安装mongodb
    sudo brew install mongodb报错
    nodemon 热更新
    npm install 之前做的事
    JS事件委托应用场景
    解决CDN传统方法引入Iview icon 不显示问题
    React 入门
  • 原文地址:https://www.cnblogs.com/hutonm/p/6236571.html
Copyright © 2011-2022 走看看