반응형
난이도 - Medium
Intuition
DFS, BFS모두 사용 가능하다. 난 여기서 BFS를 사용하였다.
Code
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_area = 0
rows = len(grid)
cols = len(grid[0])
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
grid[row][col] = -1
area = 0
queue = deque()
queue.append((row, col))
while queue:
r, c = queue.popleft()
area += 1
if r > 0 and grid[r-1][c] == 1:
grid[r-1][c] = -1
queue.append((r-1, c))
if c > 0 and grid[r][c-1] == 1:
grid[r][c-1] = -1
queue.append((r, c-1))
if r < rows-1 and grid[r+1][c] == 1:
grid[r+1][c] = -1
queue.append((r+1, c))
if c < cols-1 and grid[r][c+1] == 1:
grid[r][c+1] = -1
queue.append((r, c+1))
max_area = max(max_area, area)
return max_area
Complexity
Time Complexity: O(M*N)
Space Complexity: O(M*N)
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| 26. Remove Duplicates from Sorted Array (0) | 2025.10.25 |
|---|---|
| 169. Majority Element (Array, Hash Table, Divide and Conquer, Sorting, Counting) (0) | 2025.10.24 |
| 1047. Remove All Adjacent Duplicates In String (0) | 2025.10.24 |
| 986. Interval List Intersections (Array, Two Pointers, Line Sweep) (0) | 2025.10.24 |
| 1868. Product of Two Run-Length Encoded Arrays (Array, Two Pointers) (0) | 2025.10.24 |