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;
        }
    };
  • 相关阅读:
    接口测试相关面试题
    appium报错 Unhandled rejection Error: UiAUtomator shut down unexpectedly
    几道小题
    element-ui select 二级联动
    pycharm 永久注册
    Python-二分法查找
    python3通过qq邮箱发送邮件
    IntelliJ IDEA常用快捷键总结
    IDEA工具开发一些辅助功能设置
    类百度富文本编辑器文件上传。
  • 原文地址:https://www.cnblogs.com/hutonm/p/6236571.html
Copyright © 2011-2022 走看看