물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

463. Island Perimeter

BEstyle 2023. 1. 10. 02:56

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

 

Constraints:

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j] is 0 or 1.
  • There is exactly one island in grid.

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        
        def CountSurround(x,y,grid) -> int:
            xmax = len(grid)-1
            ymax = len(grid[0])-1
            count=0
            if 0<=x-1<=xmax and grid[x-1][y]==1:
                count+=1
            if 0<=x+1<=xmax and grid[x+1][y] ==1:
                count+=1
            if 0<=y-1<=ymax and grid[x][y-1] ==1:
                count+=1
            if 0<=y+1<=ymax and grid[x][y+1] ==1:
                count+=1
            return count
        
        ans=0
        for x in range(len(grid)):
            for y in range(len(grid[0])):
                if grid[x][y] == 1:
                    print(x,y,CountSurround(x,y,grid))
                    ans += 4-CountSurround(x,y,grid)   
        return ans

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

718. Maximum Length of Repeated Subarray  (0) 2023.01.11
706. Design HashMap  (0) 2023.01.10
283. Move Zeroes  (0) 2023.01.10
15. 3Sum  (0) 2023.01.10
42. Trapping Rain Water  (0) 2023.01.10