[LeetCode]Max Area of Island

2024. 4. 10. 18:51·SW개발/코딩테스트

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

문제 분석

주어진 그리드에서 가장 큰 섬의 크기를 구하는 문제입니다.

 

처음 시도한 답안

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])

        dx = [1,0,-1,0]
        dy = [0,1,0,-1]

        answer = 0

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    queue = [(i,j)]
                    grid[i][j] = 0
                    count = 1

                    while queue:
                        i, j = queue.pop(0)

                        for idx in range(4):
                            x = i + dx[idx]
                            y = j + dy[idx]

                            if x < 0 or y < 0 or x >= m or y >= n or grid[x][y] == 0:
                                continue

                            queue.append((x,y))
                            grid[x][y] = 0
                            count += 1

                    answer = max(answer, count)

        return answer

접근 방법

  1. 이중 포문을 순회하면서 BFS 방식으로 섬을 순회합니다.
  2. 만약 등장한 지점이 1이라면 (섬이라면)
    1. 등장한 지점을 큐에 넣고 방문 처리를 합니다.
    2. count(섬의 크기)를 1로 설정한 후 이어진 섬들을 BFS로 방문합니다.
    3. 큐에서 해당 지점을 뺀 후 상하좌우로 방문이 가능한지 확인합니다.
    4. 방문이 가능하다면 해당 지점을 큐에 넣은 후 방문 처리를 합니다.
    5. 이 때 방문이 가능하기 때문에 섬의 크기를 1 증가합니다.
    6. 가장 큰 섬의 크기를 업데이트하기 위해 answer와 count중 큰 값을 answer로 정합니다.

이어져 있는 섬을 BFS로 탐색하고 섬의 최대 크기를 저장하면서 구하면 되는 문제입니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Find All Groups of Farmland  (0) 2024.04.12
[LeetCode]Count Sub Islands  (0) 2024.04.11
[LeetCode]Valid Palindrome  (2) 2024.04.09
[LeetCode]Course Schedule  (0) 2024.04.08
[LeetCode]Number of Islands  (0) 2024.04.07
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Find All Groups of Farmland
  • [LeetCode]Count Sub Islands
  • [LeetCode]Valid Palindrome
  • [LeetCode]Course Schedule
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    음식
    배공파용
    어플리케이션
    django
    플레이스토어
    컨트리뷰터
    배달비 공유
    Contributor
    오픈소스
    g
    배달
    라이프 스타일
    트리 #AVL #알고리즘 #자료구조
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Max Area of Island
상단으로

티스토리툴바