leetcode 463. Island Perimeter(python)

描述

You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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”, meaning the water inside 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 1:

leetcode 463. Island Perimeter(python)_第1张图片

Input: grid = [[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 above.

Example 2:

Input: grid = [[1]]
Output: 4

Example 3:

Input: grid = [[1,0]]
Output: 4

Note:

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j] is 0 or 1.

解析

根据题意,要算出格子岛的边长,只需要遍历每个元素,当为 1 的时候,它的“上下左右”如果没有格子(即为 0 ),则结果 r 加一,如果有格子,因为两个格子挨着会使中间的变长消失,则不参与计算;对于第一行/列,最后一行/列比较特殊,单独进行判断,遍历结束即可得到答案。

解答

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        M, N, r = len(grid), len(grid[0]), 0
        for i in range(M):
            for j in range(N):
                if grid[i][j] == 1:
                    if i==0 or grid[i-1][j]==0: r+=1
                    if j==0 or grid[i][j-1]==0: r+=1
                    if i==M-1 or grid[i+1][j]==0: r+=1
                    if j==N-1 or grid[i][j+1]==0: r+=1
        return r

运行结果

Runtime: 392 ms, faster than 95.28% of Python online submissions for Island Perimeter.
Memory Usage: 13.8 MB, less than 28.76% of Python online submissions for Island Perimeter.

原题链接:https://leetcode.com/problems/island-perimeter/

你可能感兴趣的:(leetcode,leetcode)