Notice
Recent Posts
Recent Comments
«   2024/09   »
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
Tags
more
Archives
Today
Total
관리 메뉴

No Limitation

[BFS] 섬의 갯수 본문

프로그래밍

[BFS] 섬의 갯수

yesungcho 2024. 3. 18. 20:48

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

 

4963번: 섬의 개수

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

www.acmicpc.net

 

계속해서 반복하자. BFS 연습

여긴 특별히 대각선까지 포함한 유형이었음

from collections import deque
while True :
    N, M = [int(x) for x in input().split()]
    
    if (N,M) == (0,0):
        break

    maps = [ [int(x) for x in input().split()] for _ in range(M)]

    move_x = [-1,1,0,0,-1,1,-1,1]
    move_y = [0,0,-1,1,-1,1,1,-1]

    visited = [ [0]*N for _ in range(M) ]

    def BFS() :

        while queue :
            x, y = queue.popleft()

            for i in range(8) :
                after_x = x+move_x[i]
                after_y = y+move_y[i]

                if after_x < 0 or after_y < 0 or after_x >= M or after_y >= N :
                    continue

                if visited[after_x][after_y] == 0 and maps[after_x][after_y] == 1 :
                    queue.append([after_x,after_y])
                    visited[after_x][after_y] = 1

    count = 0
    for i in range(M) :
        for j in range(N) :
            if maps[i][j] == 1 and visited[i][j] == 0 :
                queue = deque()
                queue.append([i,j])
                BFS()
                count+=1
    print(count)