[LeetCode] Number of Islands (Python)
2024. 3. 5. 14:29ㆍ알고리즘
from collections import deque
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
islands = 0
M = len(grid)
N = len(grid[0])
visited = [[False] * N for _ in range(M)]
def bfs(x, y):
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
visited[x][y] = True
q = deque()
q.append((x, y))
while q:
cur_x, cur_y = q.popleft()
for i in range(4):
nx, ny = cur_x + dx[i], cur_y + dy[i]
if nx >= 0 and nx < M and ny >= 0 and ny < N:
if grid[nx][ny] == "1" and not visited[nx][ny]:
visited[nx][ny] = True
q.append((nx, ny))
for i in range(M):
for j in range(N):
if grid[i][j] == "1" and not visited[i][j]:
bfs(i, j)
islands += 1
return islands
'알고리즘' 카테고리의 다른 글
[LeetCode] Perfect Squares (Python) (0) | 2024.03.05 |
---|---|
[LeetCode] Open the Lock (Python) (0) | 2024.03.05 |
[백준] 14888번 : 연산자 끼워넣기 (Python3 / C++) (0) | 2020.12.29 |
[백준] 14889번 : 스타트와 링크 (Python3 / C++) (0) | 2020.12.28 |
[프로그래머스] 위장 (Python3) (0) | 2020.08.31 |