-
[Impl] BOJ 3190 ๋ฑAlgorithms in Python/baekjoon 2021. 2. 22. 13:38
๐ ๋ฐฑ์ค 3190 ๋ฑ
3190๋ฒ: ๋ฑ
'Dummy' ๋ผ๋ ๋์ค๊ฒ์์ด ์๋ค. ์ด ๊ฒ์์๋ ๋ฑ์ด ๋์์ ๊ธฐ์ด๋ค๋๋๋ฐ, ์ฌ๊ณผ๋ฅผ ๋จน์ผ๋ฉด ๋ฑ ๊ธธ์ด๊ฐ ๋์ด๋๋ค. ๋ฑ์ด ์ด๋ฆฌ์ ๋ฆฌ ๊ธฐ์ด๋ค๋๋ค๊ฐ ๋ฒฝ ๋๋ ์๊ธฐ์์ ์ ๋ชธ๊ณผ ๋ถ๋ชํ๋ฉด ๊ฒ์์ด ๋๋๋ค. ๊ฒ์
www.acmicpc.net
โ ๋ฌธ์ ์ ํต์ฌ, ํ์ด ๊ณผ์
โข ์ฌ๊ณผ๊ฐ ์๋ ์นธ๊ณผ ์๋ ์นธ, ๊ทธ๋ฆฌ๊ณ ๋ชธ์ด ์๋ ์นธ์ ๊ตฌ๋ถํ์ฌ์ผ ํ๋ค.
=> ์ฌ๊ณผ๊ฐ ์๋ ์นธ์ 1, ์ฌ๊ณผ๊ฐ ์๋ ์นธ์ 0, ์์ ์ ๋ชธ์ด ์๋ ์นธ์ -1 ๋ก ์ค์ ํ๋ค.
โข ๋ฒฝ ๋๋ ์๊ธฐ์์ ์ ๋ชธ๊ณผ ๋ถ๋ชํ๋ฉด ๊ฒ์์ด ๋๋๋ค.
=> ์ข ๋ฃ ์กฐ๊ฑด:
- ๋ฒฝ : nx < 1 or nx > n or ny < 1 or ny > n
- ์์ ์ ๋ชธ : graph[nx][ny] == -1
โข ๋ฐฉํฅ ๋ณํ ํ์ (idx)๊ฐ ๋จ์์๊ณ , ๋ฐฉํฅ์ ๋ฐ๊ฟ ๋๋ผ๋ฉด ๋ฐฉํฅ ์ ๋ณด๋ฅผ ํตํด ํด๋น ๋ฐฉํฅ์ผ๋ก ํ์ ํ๋ค.
=> ํ์ฌ ๋ฐฉํฅ d๋ฅผ ์ด์ฉํด์ ์กฐ์ํ๋ค.
โข ๊ทธ ์ธ์ ์ฐจ๋ก๋ ํ์ฌ d์ ๋ฐฉํฅ์ผ๋ก ๋ค์์นธ์ผ๋ก ์ด๋ํ๋ฉฐ ์ข ๋ฃ์กฐ๊ฑด์ธ์ง ํ์ธํ๋ค.
=> ํ์ฌ d์ ๋ฐฉํฅ์ผ๋ก ๋ค์์นธ์ ๊ฐ๋ ํจ์ go๋ฅผ ์ค์ ํ์ฌ ์์ง์ธ๋ค.
=> ์ฌ๊ณผ๊ฐ ์์ ๊ฒฝ์ฐ ๊ผฌ๋ฆฌ์ ์์นํ ์นธ์ ๋น์์ฃผ์ด์ผ ํจ์ผ๋ก, ๋ฑ์ด ์ด๋ํ ๋๋ง๋ค ๋จธ๋ฆฌ์ ์์น๋ฅผ ํ์ ๋ฃ์ด์ค๋ค.
โ ์ ์ฒด ์ฝ๋
import sys from collections import deque input = sys.stdin.readline # ๋ฐ์๊ณ ๋ฐฉํฅ ์ฐ, ํ, ์ข, ์ dx = [0, -1, 0, 1] dy = [1, 0, -1, 0] # d ๋ฐฉํฅ์ผ๋ก ๋ค์์นธ def go(): global sec, x, y nx = x + dx[d] ny = y + dy[d] # ๋จธ๋ฆฌ๊ฐ ๋ฒฝ์ ๋ฟ์์ ๋ if nx < 1 or nx > n or ny < 1 or ny > n: print(sec+1) exit() # ๋จธ๋ฆฌ๊ฐ ์์ ์ ๋ชธ๊ณผ ๋ฟ์์ ๋ if graph[nx][ny] == -1: print(sec+1) exit() q.append((nx, ny)) # ์ฌ๊ณผ๊ฐ ์์ผ๋ฉด ์ฌ๊ณผ ์์ ๊ณ ์์ ๋ชธ if graph[nx][ny] == 1: graph[nx][ny] = -1 # ์ฌ๊ณผ๊ฐ ์์ ๋ ๋ชธ ์ค์ elif graph[nx][ny] == 0: graph[nx][ny] = -1 tx, ty = q.popleft() graph[tx][ty] = 0 x, y = nx, ny sec += 1 n = int(input()) k = int(input()) graph = [[0]*(n+1) for _ in range(n+1)] info = [] for _ in range(k): a, b = map(int, input().split()) graph[a][b] = 1 l = int(input()) for _ in range(l): a, b = input().split() info.append((int(a), b)) q = deque() x, y = 1, 1 graph[x][y] = -1 q.append((x, y)) sec = 0 d = 0 idx = 0 while True: # ๋ฐฉํฅ ๋ณํ ํ์๊ฐ ๋จ์์๊ณ , ๋ฐฉํฅ์ ๋ฐ๊ฟ ๋๋ผ๋ฉด if idx < l and sec == info[idx][0]: if info[idx][1] == 'L': d = (d+1) % 4 else: d = (d-1) % 4 idx += 1 go()
'Algorithms in Python > baekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Dijkstra] BOJ 1261 ์๊ณ ์คํ (0) 2021.02.15 [Union-Find] BOJ 10775 ๊ณตํญ (0) 2021.02.08 [Stack] BOJ 17299 ์ค๋ฑํฐ์ (0) 2021.02.03 [Prefix Sum] BOJ 20002 ์ฌ๊ณผ๋๋ฌด (0) 2021.02.03 [Sliding Window] BOJ 10025 ๊ฒ์ผ๋ฅธ ๋ฐฑ๊ณฐ (0) 2021.02.03