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:
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/