LeetCode/주제별 보충

Graphs: 695. Max Area of Island ★

hyunkookim 2025. 1. 23. 14:45

695. Max Area of Island

 

BFS로 풀기

from typing import List
from collections import deque

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        # 섬 개수 및 최대 면적을 계산하는 함수
        # Count the number of islands and calculate the maximum area
        
        # 네 방향 이동: 상, 하, 좌, 우
        # Directions for movement: up, down, left, right
        directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
        
        # 그리드의 행(Row)과 열(Column) 크기
        # Number of rows and columns in the grid
        ROWS, COLS = len(grid), len(grid[0])

        # 섬의 개수 및 최대 면적을 저장할 변수
        # Variables to store the number of islands and the maximum area
        isIlands = 0  # 섬의 개수 / Number of islands
        maxArea = 0   # 섬의 최대 면적 / Maximum area of an island

        # 방문한 위치를 저장할 집합
        # Set to store visited positions
        visit = set()

        # BFS를 이용하여 섬의 면적을 계산하는 함수
        # Function to calculate the area of an island using BFS
        def bfs(r, c):
            # 큐를 생성하고 시작 위치를 추가
            # Initialize a queue and add the starting position
            q = deque()
            q.append((r, c))
            
            # 현재 위치를 방문 처리
            # Mark the current position as visited
            visit.add((r, c))
            
            # 섬의 초기 면적은 1
            # Initial area of the island is 1
            area = 1

            # BFS를 통해 연결된 섬의 영역 탐색
            # Explore connected areas of the island using BFS
            while q:
                r, c = q.popleft()
                for dr, dc in directions:
                    # 새 위치 계산
                    # Calculate new position
                    R, C = r + dr, c + dc

                    # 유효한 범위 내에서, 방문하지 않았고, 섬인 경우
                    # Check if it's within bounds, not visited, and part of the island
                    if R in range(ROWS) and C in range(COLS) and grid[R][C] == 1 and (R, C) not in visit:
                        # 큐에 추가하고 방문 처리
                        # Add to the queue and mark as visited
                        q.append((R, C))
                        visit.add((R, C))
                        
                        # 면적 증가
                        # Increment the area
                        area += 1
            
            # 탐색한 섬의 전체 면적 반환
            # Return the total area of the explored island
            return area

        # 모든 셀을 순회하며 섬을 찾음
        # Iterate through all cells to find islands
        for r in range(ROWS):
            for c in range(COLS):
                # 섬이고 방문하지 않은 경우
                # If it's part of an island and not visited
                if grid[r][c] == 1 and (r, c) not in visit:
                    # BFS를 실행하여 최대 면적 갱신
                    # Execute BFS and update the maximum area
                    maxArea = max(maxArea, bfs(r, c))
                    
                    # 섬 개수 증가
                    # Increment the island count
                    isIlands += 1

        # 섬의 최대 면적 반환
        # Return the maximum area of the islands
        return maxArea

 

DFS 로 풀기

from typing import List

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        # grid의 행과 열 크기를 구합니다.
        # Determine the number of rows and columns in the grid.
        ROWS, COLS = len(grid), len(grid[0])

        # 방문한 셀을 저장하기 위한 집합입니다.
        # A set to store visited cells.
        visit = set()

        def dfs(r, c):
            # 종료 조건: grid 경계를 벗어나거나, 물(0)이거나, 이미 방문한 경우.
            # Base case: Out of bounds, water (0), or already visited.
            if (min(r, c) < 0 or r == ROWS or c == COLS or grid[r][c] == 0 or (r, c) in visit):
                return 0

            # 현재 위치를 방문했다고 표시합니다.
            # Mark the current position as visited.
            visit.add((r, c))

            # 현재 셀(1)을 포함하여 네 방향으로 재귀 호출합니다.
            # Include the current cell (1) and recursively call in four directions.
            return (1 + dfs(r + 1, c) + dfs(r, c + 1) + dfs(r - 1, c) + dfs(r, c - 1))

        # 최대 영역을 저장할 변수입니다.
        # Variable to store the maximum area.
        area = 0

        # 모든 셀을 순회하며 DFS를 실행합니다.
        # Traverse all cells and execute DFS.
        for r in range(ROWS):
            for c in range(COLS):
                # 최대 영역을 갱신합니다.
                # Update the maximum area.
                area = max(area, dfs(r, c))

        # 최대 영역을 반환합니다.
        # Return the maximum area.
        return area

'LeetCode > 주제별 보충' 카테고리의 다른 글

Graphs: 286. Walls and Gates  (0) 2025.01.25
Graphs: 1091. Shortest Path in Binary Matrix  (0) 2025.01.23
BST: 981. Time Based Key-Value Store ★★★  (0) 2025.01.21
BST: 278. First Bad Version  (0) 2025.01.21
BST: 704. Binary Search  (0) 2025.01.21