๋ฐฑ์ค€

๋ฐฑ์ค€ 27211 ๋„๋„› ํ–‰์„ฑ - ํŒŒ์ด์ฌ

stoneeee 2023. 1. 14. 22:59

 

 

 

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

 

27211๋ฒˆ: ๋„๋„› ํ–‰์„ฑ

์ค€๊ฒธ์ด๋Š” $N \times M$์นธ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋„๋„› ๋ชจ์–‘์˜ ํ–‰์„ฑ์— ์‚ด๊ณ  ์žˆ๋‹ค. ์ค€๊ฒธ์ด๊ฐ€ ์‚ด๊ณ  ์žˆ๋Š” ํ–‰์„ฑ์—๋Š” ์œ„ ๊ทธ๋ฆผ์ฒ˜๋Ÿผ ๊ฒฉ์ž ๋ชจ์–‘์œผ๋กœ ์ค„์ด ๊ทธ์–ด์ ธ ์žˆ๋‹ค. ํ–‰์„ฑ์˜ ๊ฐ ์นธ์€ ์ˆฒ์œผ๋กœ ๋ง‰ํ˜€ ์žˆ๊ฑฐ๋‚˜, ์ง€๋‚˜๊ฐˆ ์ˆ˜

www.acmicpc.net

 

 

 

๋ฌธ์ œ์˜ ๊ทธ๋ฆผ์ด ์–ด๋งˆ๋ฌด์‹œํ–ˆ๋Š”๋ฐ... ๊ทธ๋ƒฅ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๋ฌธ์ œ์˜€๋‹ค.

4963๋ฒˆ ์„ฌ์˜ ๊ฐœ์ˆ˜, ํ˜น์€ 2667๋ฒˆ ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ์™€ ์œ ์‚ฌํ•œ ๋ฌธ์ œ์ด๋‹ค.

 

 

์œ ์ผํ•˜๊ฒŒ ์ถ”๊ฐ€๋œ ์กฐ๊ฑด์€ 0๋ฒˆ ํ–‰๊ณผ (N-1) ๋ฒˆ ํ–‰์ด ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๊ณ , 0๋ฒˆ ์—ด๊ณผ (M-1) ๋ฒˆ ์—ด์ด ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋‹ค๋Š” ์ ์ด๋‹ค.

์ด ์กฐ๊ฑด์„ ๊ณ ๋ คํ•ด์„œ ์ธ์ ‘ํ•œ ์นธ์„ ํƒ์ƒ‰ํ•  ๋•Œ 0 <= nx < N๊ณผ ๊ฐ™์€ index ์ œํ•œ ์กฐ๊ฑด์„ ๋‘๋Š” ๋Œ€์‹ , nx % N์˜ index๋ฅผ ์‚ดํŽด๋ณด๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

 

๋˜, visited ๋ฐฐ์—ด์„ ๋”ฐ๋กœ ๋งŒ๋“ค์–ด์ฃผ์ง€ ์•Š๊ณ  ๊ทธ๋ƒฅ ํƒ์ƒ‰ํ•˜๋ฉด ๋ฐ”๋กœ๋ฐ”๋กœ ์ง€๋„๋ฅผ ๊ฐฑ์‹ ํ•ด ์คฌ๋‹ค.

 

 

DFS์™€ BFS ์ค‘ ์–ด๋Š ๊ฒƒ์„ ์‚ฌ์šฉํ•ด์„œ ํ’€์–ด๋„ ์ƒ๊ด€์ด ์—†๊ฒ ์ง€๋งŒ DFS๋กœ ํ’€์—ˆ๋‹ค.

 

 

 

N, M = map(int, input().split())
world_map = [list(map(int, input().split())) for _ in range(N)]

dx, dy = [0, 0, -1, 1], [-1, 1, 0, 0]
answer = 0

for i in range(N):
    for j in range(M):
        if world_map[i][j]:
            continue

        answer += 1
        stack = [[i, j]]

        while stack:
            x, y = stack.pop()
            
            for n in range(4):
                nx = (x + dx[n]) % N
                ny = (y + dy[n]) % M

                if not world_map[nx][ny]:
                    stack.append([nx, ny])
                    world_map[nx][ny] = 1

print(answer)