[LeetCode/Python] 200. Number of Islands

도니·2025년 6월 18일

Interview-Prep

목록 보기
6/29
post-thumbnail

📌 문제

[LeetCode] 200. Number of Islands

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

📌 풀이

📌 코드 설계

📌 정답 코드

class Solution(object):
    def numIslands(self, grid):
        if not grid:
            return 0

        m, n = len(grid), len(grid[0])
        count = 0

        def dfs(x, y):
            if x < 0 or y < 0 or x >= m or y >= n or grid[x][y] == '0':
                return
            grid[x][y] = '0' # visited
            dfs(x+1 ,y) # Up
            dfs(x-1 ,y) # Down
            dfs(x, y+1) # Right
            dfs(x, y-1) # Left

        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    dfs(i, j)
                    count += 1

        return count
profile
Where there's a will, there's a way

0개의 댓글