Skip to content

Commit 1253578

Browse files
committed
[BOJ] 섬의 개수 / 실버2 / 25분
https://www.acmicpc.net/problem/4963
1 parent cd4623a commit 1253578

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from collections import deque
2+
3+
# 지도(2차원 배열)에서 섬을 탐색하기 위한 bfs
4+
def bfs(x, y):
5+
6+
# 탐색범위가 현재 노드 기준 가로, 세로, 대각선이므로 총 8가지
7+
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
8+
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
9+
10+
queue.append((x, y))
11+
visited[x][y] = 1
12+
13+
# queue가 존재하면
14+
while queue:
15+
16+
# queue에서 pop해서
17+
x, y = queue.popleft()
18+
19+
#가로, 세로 대각선에 있는 노드가 다음 세가지 조건을 만족하는지 검사
20+
# 탐색 조건
21+
# 1. 현재 노드가 배열의 인덱스 범위 안인지 0 <= row < h and 0 <= col < w
22+
# 2. 땅인지 (arr값이 1인지)
23+
# 3. 방문하지 않았는지
24+
for k in range(8):
25+
row = x + dx[k]
26+
col = y + dy[k]
27+
28+
if 0 <= row < h and 0 <= col < w and arr[row][col] == 1 and visited[row][col] == 0:
29+
queue.append((row, col))
30+
visited[row][col] = 1
31+
32+
33+
answer = deque()
34+
queue = deque()
35+
36+
while True:
37+
w, h = map(int, input().split())
38+
if h == 0 and w == 0:
39+
break
40+
41+
visited = [[0] * w for _ in range(h)]
42+
arr = [list(map(int, input().split())) for _ in range(h)]
43+
ans = 0
44+
45+
for i in range(h):
46+
for j in range(w):
47+
if arr[i][j] == 1 and visited[i][j] == 0:
48+
bfs(i, j)
49+
ans += 1
50+
51+
answer.append(ans)
52+
53+
for ans in answer:
54+
print(ans)

0 commit comments

Comments
 (0)