From 13a341fba7c706485dca4ba2b5a2ae9c249b9f02 Mon Sep 17 00:00:00 2001 From: Sony Date: Tue, 25 Jun 2019 22:29:40 +0900 Subject: [PATCH] =?UTF-8?q?[boj=201525]=20sony=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 190621/sony/boj_1525.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 190621/sony/boj_1525.py diff --git a/190621/sony/boj_1525.py b/190621/sony/boj_1525.py new file mode 100644 index 0000000..f4f7cb0 --- /dev/null +++ b/190621/sony/boj_1525.py @@ -0,0 +1,41 @@ +import sys +from collections import deque + +q = deque() +dist = dict() + +a = [list(map(int, sys.stdin.readline().split())) for _ in range(3)] +m = 0 + +for i in range(3): + for j in range(3): + n = a[i][j] + if n == 0: + n = 9 + m = m*10 + n + +def bfs(): + q.append(m) + dist[m] = 0 + + while q: + d = q.popleft() + if d == 123456789: + return dist[d] + s = str(d) + k = s.find('9') + y,x = k//3, k%3 + + for dy, dx in (-1,0), (1,0), (0,-1), (0,1): + ny, nx = y+dy, x+dx + if nx < 0 or nx >= 3 or ny < 0 or ny >= 3: continue + nk = ny*3 + nx + ns = list(s) + ns[k], ns[nk] = ns[nk], ns[k] + nd = int(''.join(ns)) + if dist.get(nd) is None: + dist[nd] = dist[d]+1 + q.append(nd) + return -1 + +print(bfs()) \ No newline at end of file