Island Perimeter

Problem Id: 463 Difficulty: Easy


Intuition

Solution


class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        ans = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    for x, y in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)):
                        if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]):
                            ans += 1
                        elif grid[x][y] == 0:
                            ans += 1
        return ans