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;
        }
    };
  • 相关阅读:
    软件对标分析
    第一阶段绩效评估
    自律小帮手:Alpha版使用说明
    团队 电梯演讲 原型展示
    意见评论
    Alpha版(内部测试版)发布
    意见汇总
    产品对比
    团队项目-第二阶段冲刺-3
    团队项目-第二阶段冲刺-2
  • 原文地址:https://www.cnblogs.com/hutonm/p/6236571.html
Copyright © 2011-2022 走看看