|
| 1 | +from collections import deque |
| 2 | + |
| 3 | +dx, dy = [-2, -1, 1, 2, 2, 1, -1, -2], [1, 2, 2, 1, -1, -2, -2, -1] #시계방향 |
| 4 | +dx2, dy2 = [-1, 1, 0, 0], [0, 0, -1, 1] #상하좌우 |
| 5 | + |
| 6 | +k = int(input()) |
| 7 | +m, n = map(int, input().split()) # m이 가로 n이 세로 |
| 8 | +arr = [] |
| 9 | +visited = [[[0] * m for _ in range(n)] for _ in range(k+1)] |
| 10 | +visited[0][0][0] = 1 |
| 11 | + |
| 12 | +for i in range(n): #맵 정보 입력 |
| 13 | + arr.append(list(map(int, input().split()))) |
| 14 | + |
| 15 | +q = deque() |
| 16 | +q.append((0, 0, 0, 0)) # x좌표, y좌표, 이동비용, 말이 움직인 횟수 |
| 17 | + |
| 18 | + |
| 19 | +def bfs(): # x -> row | y -> col |
| 20 | + while q: |
| 21 | + x, y, count, action = q.popleft() # x, y 는 좌표 정보 | count는 움직인 횟수 | action은 말의 움직임을 쓴 횟수 |
| 22 | + if x == n - 1 and y == m - 1: #목적지 도착 |
| 23 | + print(count) |
| 24 | + return |
| 25 | + |
| 26 | + for i in range(4): #상하좌우 이동 |
| 27 | + nx = x + dx2[i] |
| 28 | + ny = y + dy2[i] |
| 29 | + if action >= k: #말의 움직임을 다 쓴 경우 visited에 최대 사용가능한 말의 움직임 k로 저장한다. |
| 30 | + if 0 <= nx < n and 0 <= ny < m and visited[k][nx][ny] == 0 and arr[nx][ny] == 0: |
| 31 | + visited[k][nx][ny] = 1 |
| 32 | + q.append((nx, ny, count + 1, action)) |
| 33 | + else: #말의 움직임을 다 안 쓴 경우 현재 사용한 말의 움직임을 visited에 저장 |
| 34 | + if 0 <= nx < n and 0 <= ny < m and visited[action][nx][ny] == 0 and arr[nx][ny] == 0: |
| 35 | + visited[action][nx][ny] = 1 |
| 36 | + q.append((nx, ny, count + 1, action)) |
| 37 | + |
| 38 | + if action < k: #말의 움직임 이동 (시계방향) |
| 39 | + for i in range(8): |
| 40 | + nx = x + dx[i] |
| 41 | + ny = y + dy[i] |
| 42 | + if 0 <= nx < n and 0 <= ny < m and visited[action + 1][nx][ny] == 0 and arr[nx][ny] == 0: |
| 43 | + visited[action + 1][nx][ny] = 1 |
| 44 | + q.append((nx, ny, count + 1, action + 1)) |
| 45 | + return -1 #큐를 다 돌렸는데 목적지 도착해서 return 되지 않은 경우 -1 return |
| 46 | + |
| 47 | + |
| 48 | +if bfs() == -1: # 말의 이동 |
| 49 | + print(-1) |
0 commit comments