Skip to content

Commit 4a81cde

Browse files
committed
[22.02.25] 2667 - BFS 풀이법 추가
1 parent d620195 commit 4a81cde

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

Diff for: Python_BOJ_2022/2667.py

+39-8
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,56 @@
44
visited = [[0] * n for _ in range(n)]
55
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
66

7+
# DFS - 재귀를 이용한 풀이
8+
# cnt = 0
9+
# ans = []
10+
11+
# def recursive(x, y):
12+
# global cnt
13+
# visited[x][y] = 1
14+
# if graph[x][y] == 1:
15+
# cnt += 1
16+
# for i in range(4):
17+
# nx, ny = x + dx[i], y + dy[i]
18+
# if 0 <= nx < n and 0 <= ny <n:
19+
# if not visited[nx][ny] and graph[nx][ny] == 1:
20+
# recursive(nx, ny)
21+
22+
23+
# for i in range(n):
24+
# for j in range(n):
25+
# if graph[i][j] == 1 and not visited[i][j]:
26+
# recursive(i, j)
27+
# ans.append(cnt)
28+
# cnt = 0
29+
30+
# BFS 풀이
31+
from collections import deque
32+
733
cnt = 0
834
ans = []
935

10-
def recursive(x, y):
36+
def bfs(x, y):
1137
global cnt
38+
queue = deque()
39+
queue.append((x, y))
1240
visited[x][y] = 1
1341
if graph[x][y] == 1:
1442
cnt += 1
15-
for i in range(4):
16-
nx, ny = x + dx[i], y + dy[i]
17-
if 0 <= nx < n and 0 <= ny <n:
18-
if not visited[nx][ny] and graph[nx][ny] == 1:
19-
recursive(nx, ny)
20-
43+
while queue:
44+
x, y = queue.popleft()
45+
for i in range(4):
46+
nx, ny = x + dx[i], y + dy[i]
47+
if 0 <= nx < n and 0 <= ny < n:
48+
if graph[nx][ny] == 1 and not visited[nx][ny]:
49+
visited[nx][ny] = 1
50+
cnt += 1
51+
queue.append((nx, ny))
2152

2253
for i in range(n):
2354
for j in range(n):
2455
if graph[i][j] == 1 and not visited[i][j]:
25-
recursive(i, j)
56+
bfs(i, j)
2657
ans.append(cnt)
2758
cnt = 0
2859

0 commit comments

Comments
 (0)