마음만 바쁜 사람
Published 2022. 6. 29. 23:15
4963-섬의 개수 카테고리 없음

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

 

4963번: 섬의 개수

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

www.acmicpc.net

 

이 문제도 방향이 8가지로 늘어났다는 점만 제외하고는 아주 기본적인 문제였다. DFS와 BFS 모두 가능하지만 최근에 너무 BFS만 사용한것 같아 이번엔 DFS로 코드를 짜봤다.

 

import sys
sys.stdin = open('input.txt', 'r')

sys.setrecursionlimit(10**6)
dy = (0,1,0,-1,1,1,-1,-1)
dx = (1,0,-1,0,-1,1,-1,1)

def dfs(x,y, arr, chk):
    global w, h
    for i in range(8):
        nx, ny = x+dx[i], y+dy[i]
        if 0 <= nx < h and 0 <= ny < w and arr[nx][ny] == 1 and chk[nx][ny] == 0:
            chk[nx][ny] = 1
            dfs(nx, ny, arr, chk)

while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    m = []
    chk = [[0 for _ in range(w)] for _ in range(h)]
    ans = 0
    for _ in range(h):
        m.append(list(map(int, input().split())))
    
    for i in range(h):
        for j in range(w):
            if chk[i][j] == 0 and m[i][j] == 1:
                ans += 1
                dfs(i,j, m, chk)
    print(ans)
profile

마음만 바쁜 사람

@훌루훌루

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!