No Limitation
[BFS] 섬의 갯수 본문
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)
'프로그래밍' 카테고리의 다른 글
[코딩테스트] 완전 탐색 연습 (0) | 2024.03.20 |
---|---|
[완전 탐색] 순열 & 조합 익숙해지기 (0) | 2024.03.19 |
[완전 탐색] 기초 연습 (2) | 2024.03.18 |
[DFS] leaf node부터 count 해주는 개념 익히기 (1) | 2024.03.18 |
[BFS] 동일 SET 영역 구하기 (1) | 2024.03.17 |