463. The perimeter of the island LeetCode

463. Circumference of the Island

Easy difficulty

Given a two-dimensional grid map containing 0 and 1, where 1 represents land and 0 represents water.

The grids in the grid are connected horizontally and vertically (diagonally not connected). The entire grid is completely surrounded by water, but there is exactly one island (or an island connected by one or more grids representing land).

There is no "lake" in an island (a "lake" means that the water is inside the island and not connected to the water around the island). The grid is a square with one side. The grid is rectangular, and neither the width nor the height exceeds 100. Calculate the perimeter of this island.

 

Example:

enter:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: Its perimeter is the 16 yellow edges in the picture below:

Source: LeetCode

Link: https://leetcode-cn.com/problems/island-perimeter

The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

 

Problem-solving ideas:

# 1. The perimeter length of each land = 4-the sum of the number of surrounding land. contact = {1:3,2:2,3:1,4:0}
# 2. Add a circle of 0 around, representing the water area, so that when traversing the original grid, there is no need to consider boundary issues

 

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        # 1. 每个陆地周边长度 = 4 - 其周边陆地个数之和。contact = {1:3,2:2,3:1,4:0}
        # 2. 周围加一圈0,代表水域,这样遍历原有grid时,不需要考虑边界问题

        if len(grid) == 0:
            return 0
        grid.insert(0, [0] * len(grid[0]))
        grid.append([0] * len(grid[0]))
        for i in range(len(grid)):
            grid[i].insert(0, 0)
            grid[i].append(0)
        p = 0
        # 遍历原grid
        for i in range(1, len(grid)-1):
            for j in range(1, len(grid[0])-1):
                if grid[i][j] == 1:
                    p += 4 - sum([grid[i-1][j], grid[i+1][j], grid[i][j-1], grid[i][j+1]])
        return p

            The answer was successful:
            execution time: 128 ms, defeating 93.85% of Python3 users
            Memory consumption: 13.9 MB, defeating 23.97% of Python3 users

Guess you like

Origin blog.csdn.net/authorized_keys/article/details/109383896