본문 바로가기
Leetcode

[LeetCode] Island Perimeter 파이썬 (island, traverse)

by YGSEO 2021. 4. 19.
728x90

풀이방법:

2-d array를 traverse하면서 (row col)

land 일 경우 4를 더해준다.

단, land일 경우 land의 위쪽과 왼쪽일 경우 -2를 더해준다.

왼쪽과 위쪽만 체크하는 이유는 traverse의 방향 때문에 그렇다.

 

그림으로 설명

오른쪽 아래 land 기준으로

위의 land에서 한개, 오른쪽 아래 land에서 한개

겹치는 land가 있을 때마다 2개씩 빼줘야 한다.

여기서는 grid의 side length를 1로 주어졌기 때문에 그냥 2를 빼주면 된다.

 

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        count, repeat = 0, 0

        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 1:
                    count += 1
                    if i != 0 and grid[i - 1][j] == 1:
                        repeat += 1
                    if j != 0 and grid[i][j - 1] == 1:
                        repeat += 1

        return 4*count - 2*repeat
class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        result = 0

        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 1:
                    result += 4
                    if i != 0 and grid[i - 1][j] == 1:
                        result -= 2
                    if j != 0 and grid[i][j - 1] == 1:
                        result -= 2

        return result

 

풀이 설명 출처: www.youtube.com/watch?v=FkjFlNtTzc8

코드 출처: github.com/jiapengwen/LeetCode/blob/master/Python/island-perimeter.py

 

728x90

댓글