中级农民
- 积分
- 114
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-11-23
- 最后登录
- 1970-1-1
|
发两个解法
求大米
- import heapq
- import numpy as np
- import matplotlib.pyplot as plt
- def min_turn_bfs(map, src, dst):
- if src == dst:
- return 0, [src]
- m, n = map.shape
- q = [(0, (0,0), [src])]
- while len(q) > 0:
- n_turns, current_direction, path = heapq.heappop(q)
- print(q)
- for direction in ((1,0), (0,1), (-1,0), (0,-1)):
- loc = (path[-1][0]+direction[0], path[-1][1]+direction[1])
- if loc[0] < 0 or loc[0] >= m or loc[1] < 0 or loc[1] >= n or map[loc[0],loc[1]] != 0 or loc in path: # path can be optimized with set
- continue
- n_turns_next = n_turns
- if direction != current_direction:
- n_turns_next += 1
- path_next = path + [loc]
- if loc == dst:
- return n_turns_next, path_next
- heapq.heappush(q, (n_turns_next, direction, path_next))
- return np.inf, []
- def min_turn_dfs(map, src, dst, current_direction = None):
- if src == dst:
- return 0, [src]
- m, n = map.shape
- ret = np.inf
- ret_path = []
- for direction in ((1,0), (0,1), (-1,0), (0,-1)):
- loc = (src[0]+direction[0], src[1]+direction[1])
- if loc[0] < 0 or loc[0] >= m or loc[1] < 0 or loc[1] >= n or map[loc[0],loc[1]] != 0:
- continue
- map[loc[0],loc[1]] = -1
- n_turns, path = min_turn(map, loc, dst, direction)
- map[loc[0],loc[1]] = 0
- if direction != current_direction:
- n_turns += 1
- if ret > n_turns:
- ret = n_turns
- ret_path = [src] + path
- return ret, ret_path
- map = np.zeros((5,5))
- map[1,1] = 1
- map[2,2] = 1
- map[3,3] = 1
- map[3,0] = 1
- map[4,1] = 1
- n_turns, path = min_turn_bfs(map, (1,0), (4,2))
- print(n_turns, path)
- for p in path:
- map[p[0],p[1]] = -1
- plt.figure()
- plt.imshow(map)
- plt.show()
复制代码 |
|