Post

๐Ÿน ๋กœ๋ด‡์ฒญ์†Œ๊ธฐ

1. ๋ฌธ์ œ ๋งํฌ

14503๋ฒˆ: ๋กœ๋ด‡ ์ฒญ์†Œ๊ธฐ


2. ์ฝ”๋“œ

Python3 31256KB 72ms

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from collections import deque

N, M = map(int, input().split())
r, c, d = map(int, input().split())
place = []
for _ in range(N):
    place.append(list(map(int, input().split())))

# ๋ถ, ๋™, ๋‚จ, ์„œ
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

def bfs(x, y, d):
    q = deque([])
    q.append((x, y, d))
    place[x][y] = 2
    cnt = 1 # ์ฒญ์†Œํ•œ ์นธ์˜ ๊ฐœ์ˆ˜
    while q:
        x, y, d = q.popleft()
        # ํ˜„์žฌ ์œ„์น˜ํ•œ ์นธ์ด ์ฒญ์†Œ๊ฐ€ ์•ˆ ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ
        if place[x][y] == 0:
            place[x][y] = 2 # ์ฒญ์†Œํ•˜๋ฉด 2
            cnt += 1
        # ํ˜„์žฌ ์œ„์น˜ํ•œ ์นธ์ด ์ฒญ์†Œ๊ฐ€ ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ
        if place[x][y] == 2:
            clean = True
            for i in range(1, 5):
                now_d = ((d - i) + 4) % 4   # ๋ฐ˜์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ 90๋„ ํšŒ์ „
                nx = x + dx[now_d]
                ny = y + dy[now_d]
                # ํ˜„์žฌ ์นธ์˜ ์ฃผ๋ณ€ 4์นธ ์ค‘ ์ฒญ์†Œ๋˜์ง€ ์•Š์€ ์นธ์ด ์žˆ๋Š” ๊ฒฝ์šฐ
                if 0 <= nx < N and 0 <= ny < M and place[nx][ny] == 0:
                    clean = False
                    place[nx][ny] = 2
                    cnt += 1
                    q.append((nx, ny, now_d))
                    break
            # ํ˜„์žฌ ์นธ์˜ ์ฃผ๋ณ€ 4์นธ ์ค‘ ์ฒญ์†Œ๋˜์ง€ ์•Š์€ ์นธ์ด ์—†๋Š” ๊ฒฝ์šฐ
            if clean == True:
                back = (d + 2) % 4  # ํ›„์ง„ ๋ฐฉํ–ฅ
                nx = x + dx[back]
                ny = y + dy[back]
                # ํ›„์ง„ํ•˜๋ฉด ๋ฒฝ์— ๋ถ€๋”ชํžˆ๋Š” ๊ฒฝ์šฐ
                if 0 <= nx < N and 0 <= ny < M and place[nx][ny] == 1:
                    return cnt  # ์ž‘๋™์„ ๋ฉˆ์ถ˜๋‹ค
                else:
                    q.append((nx, ny, d))   # ๋ฐฉํ–ฅ์€ ๊ฐ™์Œ
    return cnt

print(bfs(r, c, d))


3. ํ•ด์„ค

bfs๋ฅผ ์ด์šฉํ•ด ์ฃผ์–ด์ง„ ๋ฐฉํ–ฅ์— ๋”ฐ๋ผ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ๋ชจ๋“  ๋ฐฉ์„ ํƒ์ƒ‰ํ•˜๊ณ  ์ฒญ์†Œํ•œ๋‹ค.

๋ฐฉํ–ฅ์„ ๋ณ€๊ฒฝํ•  ๋•Œ ํ›„์ง„ํ•˜๋Š” ๊ฒฝ์šฐ dx, dy ์ธ๋ฑ์Šค๋ฅผ 2์ฐจ์ด ๋‚˜๋„๋ก ๋ณ€๊ฒฝํ•œ๋‹ค. ์ด๋•Œ ๋ฐ”๋ผ๋ณด๋Š” ๋ฐฉํ–ฅ์€ ๋™์ผํ•˜๋‹ค.

์ฒญ์†Œ๋œ ์นธ โ†’ 2๋กœ ๋ณ€๊ฒฝ

queue์— ๋ณ€๊ฒฝ๋œ x,y ์œ„์น˜์™€ ๋ฐ”๋ผ๋ณด๋Š” ๋ฐฉํ–ฅ์„ ๋„ฃ๊ณ , queue๊ฐ€ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ๊ตฌ์—ญ์„ ๋Œ๋ฉด ๋œ๋‹ค.

This post is licensed under CC BY 4.0 by the author.