[https://programmers.co.kr/learn/courses/30/lessons/72415]
ํ์ด
2021 ์นด์นด์ค ๋ฌธ์ ์ธ, ์นด๋ ์ง ๋ง์ถ๊ธฐ ๋ผ๋ ๋ฌธ์ ์ด๋ค.
์ฒ์ ๋ดค์ ๋, ์ด๋ป๊ฒ ํ์ด์ผ ํ ์ง ๊ฐ์ด ์ค์ง ์์๋ค.
๊ทธ๋ฌ๋ค ์กฐ๊ฑด์ด 4x4 ๋ฐฐ์ด์์ ํ์ธํ๊ณ .. "์ ์ ๋ถ ๋ค ํ
์คํธ ํด๋ณด๋ผ๋๊ฑฐ๊ตฌ๋.."
ํน์ ์์น์์ ๊ฒฝ์ฐ์ ์๋ 9๊ฐ์ง์ด๋ค.
- 4๋ฐฉํฅ ์ด๋
- 4๋ฐฉํฅ Ctrl ์ด๋
- Enter
๋ง ๊ทธ๋๋ก ๋ชจ๋ ๋ค ๊ตฌํํ๋ค.
๊ทธ๋ฆฌ๊ณ ๋ฐฐ์ด์ ๋ฌธ์์ด๋ก ์์ ํด์ ํ์๋ค.
๊ทธ ์ด์ ๋ ํ์ด์ฌ์์ ๋ฐฐ์ด์ mutableํ object ์ด๋ฏ๋ก ๊ณ์ deep copyํด์ฃผ๊ธฐ๊ฐ ๊ท์ฐฎ์๋ค.
์์งํ ๋ด ์ฝ๋๊ฐ ๋ง์์ ๋ค์ง๋ ์๋๋ฐ, ์๋ก์ด ๋ฌธ์ ๋ผ ๋ค๋ฅธ ๋ถ๋ค์ด ํฌ์คํ
ํ ์ข์ ์ฝ๋๋ฅผ ๋ฐ๊ฒฌํ์ง๋ ๋ชปํ๋ค.
์นด์นด์ค ๋ฌธ์ ์์ ๊ตฌํ์ด ์กฐ๊ธ ํ๋ํ ๋ฌธ์ ๊ฐ ๋ง์ด ๋์ค๋๊ตฌ๋ ๊นจ๋ฌ์๋ ๋ฌธ์ ์๋ค.
from collections import deque
import copy
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def end_game(b):
if b.count("0") == 16:
return True
return False
def remove_element(b, e):
b = b.replace(e, "0")
return b
def move(b, y, x, dy, dx):
ny, nx = y + dy, x + dx
if ny >= 0 and ny < 4 and nx >= 0 and nx < 4 and b[ny * 4 + nx] == "0":
return move(b, ny, nx, dy, dx)
else:
if ny >= 0 and ny < 4 and nx >= 0 and nx < 4:
return (ny, nx)
else:
return (y, x)
def solution(board, r, c):
answer = 0
b = ""
for i in range(4):
for j in range(4):
b += str(board[i][j])
q = deque([])
cnt = 0
enter = -1 # enter์ ํด๋ฆญํ๋ ์์น
q.append((r, c, b, cnt, enter))
s = set()
while q:
y, x, b, c, e = q.popleft()
pos = 4 * y + x
if (y, x, b, e) in s:
continue
s.add((y, x, b, e))
if end_game(b):
return c
# 4 ๋ฐฉํฅ ์ด๋
for (dy, dx) in d:
ny, nx = y + dy, x + dx
if ny >= 0 and ny < 4 and nx >= 0 and nx < 4:
q.append((ny, nx, b, c+1, e))
# Ctrl + 4 ๋ฐฉํฅ ์ด๋
for (dy, dx) in d:
ny, nx = move(b, y, x, dy, dx)
if ny == y and nx == x:
continue
q.append((ny, nx, b, c+1, e))
# enter๋ฅผ ํ๋ ๊ฒฝ์ฐ
if b[pos] != 0:
if e == -1:
n_e = pos
q.append((y, x, b, c+1, n_e))
else:
if e != pos and b[e] == b[pos]:
b = remove_element(b, b[e])
q.append((y, x, b, c+1, -1))
return answer'Problem Solving ๐ฅ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [ํ๋ก๊ทธ๋๋จธ์ค] ๋ณด์ ์ผํ / ํ์ด์ฌ / ํฌ ํฌ์ธํฐ (0) | 2021.01.27 |
|---|---|
| [ํ๋ก๊ทธ๋๋จธ์ค] ํฉ์น ํ์ ์๊ธ / ํ์ด์ฌ / (ํ๋ก์ด๋ ์์ฌ) (0) | 2021.01.26 |
| [ํ๋ก๊ทธ๋๋จธ์ค] ๋ฐฉ๋ฌธ ๊ธธ์ด / ํ์ด์ฌ (0) | 2021.01.24 |
| [ํ๋ก๊ทธ๋๋จธ์ค] ์ผ๊ทผ ์ง์ / ํ์ด์ฌ (0) | 2021.01.24 |
| [ํ๋ก๊ทธ๋๋จธ์ค] ์ธ๋ฒฝ ์ ๊ฒ / ํ์ด์ฌ (0) | 2021.01.23 |