728x90
반응형
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
문제 해결
움직일 수 있는 방향이 동서남북 대각선까지 총 8가지이다.
한 점을 잡고 갈수 있는 끝까지 가면서 Land를 Sea로 바꾸는 작업을 한다.
더이상 갈 수 없으면 다음 Land점을 잡고 똑같은 일을 한다.
이를 DFS로 코드를 만들 수 있다.
백준은 sys.setrecursionlimit()를 꼭 써야하는 것 같다.
CODE
import sys
input = sys.stdin.readline
sys.setrecursionlimit(5000)
def solve(row,col):
global board
board[row][col] = 0
for i in range(len(move)):
idx = move[i][0]
idy = move[i][1]
new_row = row+idx
new_col = col + idy
if 0<=new_row and new_row<h and 0<=new_col and new_col<w and board[new_row][new_col] == 1:
solve(new_row, new_col)
while 1:
w, h = map(int, input().split())
if w==0 and h ==0:
break
board = [list(map(int, input().split())) for _ in range(h)]
move = [(1,0), (0,1), (-1,0), (0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]
cnt = 0
for col in range(w):
for row in range(h):
if board[row][col] ==1:
cnt +=1
solve(row,col)
print(cnt)
728x90
반응형
'알고리즘 > [python] 백준 BOJ' 카테고리의 다른 글
[Python] 백준 16947 서울 지하철 2호선 (0) | 2023.01.24 |
---|---|
[python] 백준 16929 Two Dots (0) | 2023.01.23 |
[python] 백준 11724 연결 요소의 개수 (1) | 2023.01.22 |
[python] 백준 13023 ABCDE (0) | 2023.01.22 |
[python] 백준 14391 종이 조각 (0) | 2023.01.21 |
댓글