463. Island Perimeter(python+cpp)

题目:

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:
在这里插入图片描述

解释:
求岛屿的周长。
先让每一块陆地的周长都为4,遍历的时候,如果该块陆地的左边或者上边(右边或者下边 或者其他两种随机组合)也是陆地,则总周长减去2(因为毗邻部分有两条边需要去掉),注意不能4个边都减去,因为一个的左边或者上边有,相当与另一个的右边或者下边有,如果四个都减去的话会重复;或者可以四周都查看一下,但是每次减去的就是一条边而不是两条边,注意取值范围。
pytho代码:

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        result=0
        height=len(grid)
        width=len(grid[0]) if height else 0
        for i in xrange (height):
            for j in xrange(width):
                if grid[i][j]==1:
                    result+=4
                    if i>0 and grid[i-1][j]==1:
                        result-=2
                    if j>0 and grid[i][j-1]==1:
                        result-=2
        return result

c++代码:

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int m=grid.size();
        if (m==0)
            return 0;
        int n=grid[0].size();
        int result=0;
        for (int i=0;i<m;i++)
        {
            for (int j=0;j<n;j++)
            {
                if (grid[i][j]==1)
                {
                    result+=4;
                    if (i>0 &&grid[i-1][j]==1)
                        result-=2;
                    if (j>0 &&grid[i][j-1]==1)
                        result-=2;
                }
            }
        }
        return result;
    }
};

总结:
单纯的逻辑题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值