[解题笔记] LeetCode 7月挑战题目之7

Island Perimeter

这是我第一次参加 LeetCode (力扣) 的每月挑战题组,希望留下点笔记,大家可以参考和互相讨论。😃

第七天问:

现在给你一个二维网格地图,里面每个1代表土地,0代表水面。每一个格子都只能是橫向或者竖向相连 (不会斜向相连),而且这个地图上只有一个陸地。

已知:

  1. 陸地不会有「河流」,意思是「水」(数字0) 只能在陸地上下左右存在,不会在陸地之间相连;
  2. 每个格子的四条边界都是 1 ;
  3. 这个地图网格是一个长方形,长度和宽度都不多于 100。

请写一个程序来求这网格的边长。

题目例子 (引用自LeetCode):

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

Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:

在这里插入图片描述

解题思路:

我想到一个比较简单的方法 (今天时间不多,只想到一个),就是一个一个格子1逐个看,用 if-clause 查它的上下左右有沒有格子,如果沒有就在总参数 (perimeter) 加一。但是,坏处是因为需要一个个的看,所以时间需求挺大的。

代码一 (时间复杂度:O(​n2))

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        if grid == [[1]]:
            return 4
        perimeter = 0
        for row in range(len(grid)):
            for coln in range(len(grid[row])):
                if grid[row][coln] == 0:
                    continue
                if row == 0 or grid[row -1][coln] == 0:
                    perimeter += 1
                if coln == 0 or grid[row][coln - 1] == 0:
                    perimeter += 1
                if row == len(grid) - 1 or grid[row + 1][coln] == 0:
                    perimeter += 1
                if coln == len(grid[row]) - 1 or grid[row][coln + 1] == 0:
                    perimeter += 1
        return perimeter 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值