lc463. Island Perimeter

245 阅读1分钟
  1. Island Perimeter Easy

2056

121

Add to List

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

思路:leetcode-cn.com/problems/is… 太优秀,发个链接

代码:python3

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        def dfs(grid,r,c):
            if not (r>=0 and r<len(grid) and c>=0 and c<len(grid[0])):
                return 1
            print(c)
            print(r)
            if grid[r][c] ==0:
                print(r+c)
                return 1
            if grid[r][c] != 1:
                print(r+c)
                return 0
            grid[r][c]=2
            return dfs(grid,r+1,c)+dfs(grid,r-1,c)+dfs(grid,r,c+1)+dfs(grid,r,c-1)

        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]==1:
                    return dfs(grid,i,j);
if __name__ == '__main__':
    print(Solution().islandPerimeter([[0,1]]))

时间复杂度:O(m^2) 空间复杂度:O(m^2)