티스토리 뷰

728x90

https://www.acmicpc.net/problem/4963

 

4963번: 섬의 개수

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도

www.acmicpc.net

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def bfs(x, y):
    global cnt
    queue.append([x, y])
    visit[x][y] = True
    while queue:
        x, y = queue[0][0], queue[0][1]
        del queue[0]
        if lst[x][y] == 1:
            cnt = 1
        for dx, dy in direction:
            nx, ny = x + dx, y + dy
            if 0 <= nx < h and 0 <= ny < w and lst[nx][ny] == 1 and not visit[nx][ny]:
                visit[nx][ny] = True
                queue.append([nx, ny])
 
 
while True:
    queue = []
    w, h = map(int, input().split())
    island = 0
    if w == 0 and h == 0:
        break
    lst = [[] * w for _ in range(h)]
    visit = [[False] * w for _ in range(h)]
    direction = [(0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)]
    cnt = 0
    for i in range(h):
        lst[i] = list(map(int, input().split()))
    for i in range(h):
        for j in range(w):
            if lst[i][j] == 1 and not visit[i][j]:
                bfs(i, j)
                island += cnt
    print(island)
cs

 

댓글