[leetcode] 200. Number of Islands(medium)

Erdos·2024년 2월 20일
0

코딩테스트

목록 보기
14/20

🤔🤔🤔🤔🤔🤔

문제

https://leetcode.com/problems/number-of-islands/description/

풀이

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        def dfs(i, j):
            # 더 이상 땅이 아닌 경우 종료
            if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != '1':
                return

            grid[i][j] = 0

            # 동서남북 탐색
            dfs(i + 1, j)
            dfs(i - 1, j)
            dfs(i, j + 1)
            dfs(i, j - 1)

        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '1':
                    dfs(i, j)
                    # 모든 육지 탐색 후 카운트 1 증가
                    count += 1
        return count

다른 풀이

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0

        count = 0

        visited = set()
        r, c = len(grid), len(grid[0])

        def bfs(startI, startJ):
            queue = collections.deque()
            visited.add((startI, startJ))
            queue.append((startI, startJ))

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

                if i+1 < r and grid[i+1][j] == "1" and (i+1, j) not in visited:
                    queue.append((i+1, j))
                    visited.add((i+1, j))

                if i-1 >= 0 and grid[i-1][j] == "1" and (i-1, j) not in visited:
                    queue.append((i-1, j))
                    visited.add((i-1, j))

                if j+1 < c and grid[i][j+1] == "1" and (i, j+1) not in visited:
                    queue.append((i, j+1))
                    visited.add((i, j+1))

                if j-1 >= 0 and grid[i][j-1] == "1" and (i, j-1) not in visited:
                    queue.append((i, j-1))
                    visited.add((i, j-1))

        
        for i in range(r):
            for j in range(c):
                if grid[i][j] == "1" and (i, j) not in visited:
                    count += 1
                    bfs(i, j)

        return count
profile
수학을 사랑하는 애독자📚 Stop dreaming. Start living. - 'The Secret Life of Walter Mitty'

0개의 댓글