463. Island Perimeter (C++)

题目:

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
https://leetcode.com/problems/island-perimeter/?tab=Description

翻译:

您将获得一个二维整数网格形式的地图,其中1表示土地,0表示水。 网格单元水平/垂直(不是对角线)连接。 网格完全被水包围,并且恰好有一个岛(即,一个或多个连接的陆地单元)。 岛上没有“湖泊”(里面的水是不连接到岛周围的水)。 一个单元格是边长为1的正方形。网格是矩形,宽度和高度不超过100.确定岛的周长。

思路:

主要就是找规律,就想过马路一样,行人都是往前看,往右看,遵守这条规律,大家都不会发生碰撞(产生冗余)
找规律制定规则:
1. 遇到“1”时计数器“+4“,因为一个单独存在与空间的方格有四个边。
2. 向右看,向下看,如果发现有“1”则计数器“-2”,发现一次减一次,发现两次减两次,因为两个连在一起的话总线条数会减少两条。
3. 每次遍历先略过最右边一列以及最下边一行这些边界情况,因为它们的规则不太一样。
4. 边界规则:最右边一列遇到“1”只看下面有没有“1”,没有右边的所以不看。最下面一行遇到“1”只看右边有没有“1”,因为他下面没有东西。边界情况身边有“1”则计数器“-2”。边界规则不包含最右下角的那个元素,因为它既没有右边也没有下边。
5. 最右下角元素:如果是“1”,计数器“+4”,不用担心左边上面,因为该减的都减过了。

解答:

把上面的规则按顺序写下来就是答案
下面是我给出的答案,(84.23%,132ms)

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
  int row = grid.size();
    if (!row)
        return 0;
    int col = grid[0].size();
    if (!col)
        return 0;
    int ret = 0;
    for (int i = 0; i < row-1; ++i)
    {
        for (int j = 0; j < col-1; ++j)
        {
            if (grid[i][j] == 1)
            {
                ret += 4;
                if (grid[i + 1][j] == 1) ret -= 2;
                if (grid[i][j + 1] == 1) ret -= 2;
            }
        }
    }
    for (int i = 0; i < row - 1; ++i)
    {
        if (grid[i][col-1] == 1)
        {
            ret += 4;
            if (grid[i + 1][col-1] == 1) ret -= 2;
        }
    }
    for (int i = 0; i < col - 1; ++i)
    {
        if (grid[row-1][i] == 1)
        {
            ret += 4;
            if (grid[row-1][i+1] == 1) ret -= 2;
        }
    }
    if (grid[row-1][col-1] == 1)
    {
        ret += 4;
        /*if (grid[row - 2][col - 1] == 1)
        {
            ret--;
        }
        if (grid[row - 1][col - 2] == 1)
        {
            ret--;
        }*/
    }
    return ret;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值