DevYoon

[SWEA] 1953. ํƒˆ์ฃผ๋ฒ” ๊ฒ€๊ฑฐ (Python) ๋ณธ๋ฌธ

PS/SWEA

[SWEA] 1953. ํƒˆ์ฃผ๋ฒ” ๊ฒ€๊ฑฐ (Python)

gimewn 2022. 4. 5. 23:59

link ๐Ÿ”— https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PpLlKAQ4DFAUq 

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

 

1๏ธโƒฃ BFS ์‚ฌ์šฉ

2๏ธโƒฃ ์ƒ ํ•˜ ์ขŒ ์šฐ → ๊ฐ ๋ฐฉํ–ฅ์—์„œ ์—ฐ๊ฒฐ ๊ฐ€๋Šฅํ•œ ํŒŒ์ดํ”„ ๋ฒˆํ˜ธ ํ•˜๋“œ์ฝ”๋”ฉ

3๏ธโƒฃ 1๋ถ€ํ„ฐ 7๊นŒ์ง€, ๋ฒˆํ˜ธ์— ๋”ฐ๋ผ ์—ฐ๊ฒฐ ๊ฐ€๋Šฅํ•œ ๋ฐฉํ–ฅ ์ง€์ •

 

from collections import deque
 
def bfs(y, x):
    q = deque()
    q.append((y, x, 1)) # y, x, time
    while q:
        nowy, nowx, time = q.popleft()
        if time == L:
            return
        directy = [-1, 1, 0, 0]  # ์ƒ ํ•˜ ์ขŒ ์šฐ
        directx = [0, 0, -1, 1]
        pipe = [[1, 2, 5, 6], [1, 2, 4, 7], [1, 3, 4, 5], [1, 3, 6, 7]] # ์ƒ ํ•˜ ์ขŒ ์šฐ ์—ฐ๊ฒฐ ๊ฐ€๋Šฅํ•œ ํŒŒ์ดํ”„
        if arr[nowy][nowx] == 1:  # ์ƒ ํ•˜ ์ขŒ ์šฐ
            temp = [x for x in range(4)]
        elif arr[nowy][nowx] == 2:  # ์ƒ ํ•˜
            temp = [0, 1]
        elif arr[nowy][nowx] == 3:  # ์ขŒ ์šฐ
            temp = [2, 3]
        elif arr[nowy][nowx] == 4:  # ์ƒ ์šฐ
            temp = [0, 3]
        elif arr[nowy][nowx] == 5:  # ํ•˜ ์šฐ
            temp = [1, 3]
        elif arr[nowy][nowx] == 6:  # ํ•˜ ์ขŒ
            temp = [1, 2]
        else:  # ์ƒ ์ขŒ
            temp = [0, 2]
 
        for t in temp:
            dy = directy[t] + nowy
            dx = directx[t] + nowx
            if 0 <= dy < N and 0 <= dx < M:
                if check[dy][dx] != 1 and arr[dy][dx] in pipe[t]:
                    check[dy][dx] = 1
                    q.append((dy, dx, time+1))
 
t = int(input())
 
for tc in range(1, t+1):
    N, M, R, C, L = map(int, input().split()) # ์„ธ๋กœ ํฌ๊ธฐ, ๊ฐ€๋กœ ํฌ๊ธฐ, ๋งจํ™€ x์ขŒํ‘œ, ๋งจํ™€ y์ขŒํ‘œ, ์‹œ๊ฐ„
    arr = [list(map(int, input().split())) for _ in range(N)]
    check = [[0]*M for _ in range(N)]
    cnt = 0
    check[R][C] = 1
    bfs(R, C)
 
    for i in range(N):
        for j in range(M):
            if check[i][j] == 1:
                cnt += 1
 
    print(f'#{tc} {cnt}')