1 import queue
2
3 # 地图
4 maps = []
5 # 分别代表鸣人和佐助的位置
6 r1, c1, r2, c2 = 0, 0, 0, 0
7 # 访问标记
8 visited = []
9 # 四个方向数组
10 direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
11
12
13 class Node:
14 # 所在位置
15 r = 0
16 c = 0
17 # 查克拉剩余
18 t = 0
19 # 所在层数,路径长度
20 level = 0
21
22 def __init__(self, rr, cc, tt, level1):
23 self.r = rr
24 self.c = cc
25 self.t = tt
26 self.level = level1
27
28
29 # 获取鸣人和佐助的r,c
30 def getTwoDimensionListIndex(list_map, value):
31 r, c = 0, 0
32 for i in range(len(list_map)):
33 for j in range(len(list_map[i])):
34 if list_map[i][j] == value:
35 r = i
36 c = j
37 break
38 return r, c
39
40
41 def bfs(r, c, k):
42 global maps, r1, c1, r2, c2, visited
43 new_node = Node(r1, c1, k, 0)
44 q = queue.Queue()
45 q.put(new_node)
46 while not q.empty():
47 temp = q.get()
48 # 找到佐助
49 if temp.r == r2 and temp.c == c2:
50 cost_time = temp.level
51 return cost_time
52 # 把当前节点四个方向的节点入队
53 for i in range(4):
54 temp2 = Node(0, 0, 0, 0)
55 temp2.r = temp.r + direction[i][0]
56 temp2.c = temp.c + direction[i][1]
57 # 保证访问的点不越界
58 if 0 <= temp2.r < r and 0 <= temp2.c < c:
59 # 若为"#"并且查克拉够 并且没访问过 可访问
60 if maps[temp2.r][temp2.c] == "#" and temp.t >= 1 and visited[temp2.r][temp2.c][temp.t-1] == 0:
61 temp2.t = temp.t - 1
62 temp2.level = temp.level + 1
63 q.put(temp2)
64 visited[temp2.r][temp2.c][temp2.t] = 1
65 # 不是# 并且未访问过
66 elif maps[temp2.r][temp2.c] != "#" and visited[temp2.r][temp2.c][temp.t] == 0:
67 temp2.t = temp.t
68 temp2.level = temp.level + 1
69 q.put(temp2)
70 visited[temp2.r][temp2.c][temp2.t] = 1
71 return 0
72
73
74 def main():
75 global maps, r1, c1, r2, c2, visited
76 # k-查克拉的数量
77 r, c, k = map(int, input().split())
78
79 for i in range(r):
80 temp = list(input())
81 maps.append(temp)
82 # [['#', '@', '#', '#'],['*', '*', '#', '#'],
83 # ['#', '#', '#', '+'],['*', '*', '*', '*']]
84 # 查找鸣人和佐助的位置
85 r1, c1 = getTwoDimensionListIndex(maps, "@")
86 r2, c2 = getTwoDimensionListIndex(maps, "+")
87 visited = [[[0 for i in range(k+1)] for j in range(c)] for e in range(r)]
88 """
89 三维的visited列表
90 [
91 [[0, 0], [0, 0], [0, 0], [0, 0]],
92 [[0, 0], [0, 0], [0, 0], [0, 0]],
93 [[0, 0], [0, 0], [0, 0], [0, 0]],
94 [[0, 0], [0, 0], [0, 0], [0, 0]]
95 ]
96 """
97 # 从这里出发,置状态为1,表示访问过
98 visited[r1][c1][k] = 1
99 rtn = bfs(r, c, k)
100 if rtn == 0:
101 print("-1")
102 else:
103 print("鸣人追上佐助最少需要花费的时间为:%d" % rtn)
104
105
106 if __name__ == '__main__':
107 main()