본문 바로가기

두두의 알고리즘/문제

[BFS] 릿코드 Medium 695 'Max Area of Island' (Python)

728x90

<문제 링크>

https://leetcode.com/problems/max-area-of-island/

 

Max Area of Island - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


<문제 풀이>

  • 상하좌우로 1이 연결된 면적 구하기
  • 최대 면적 구하기

 

<코드>

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        tmp = 0
        answer = 0
        dx = [-1,0,1,0]
        dy = [0,-1,0,1]
        
        for x in range(len(grid)):
            for y in range(len(grid[0])):
                if grid[x][y] == 1:
                    grid[x][y] = 2
                    tmp += 1
                    q = [(x,y)]
                    while q:
                        xpop, ypop = q.pop(0)
                        for d in range(4):
                            nx = xpop+dx[d]
                            ny = ypop+dy[d]
                            if nx>=0 and nx<len(grid) and ny>=0 and ny<len(grid[0]) and grid[nx][ny]==1:
                                grid[nx][ny] = 2
                                tmp += 1
                                q.append((nx,ny))
                if tmp>answer:
                    answer = tmp
                tmp = 0
        
        return answer

 

<고쳐야 할 점>

  • 문제 잘 이해하기