N*M格子捡苹果DP算法python

转载陈述:

http://www.hawstein.com/posts/dp-novice-to-advanced.html

平面上有N*M个格子,每个格子中放着一定数量的苹果。你从左上角的格子开始, 每一步只能向下走或是向右走,每次走到一个格子上就把格子里的苹果收集起来, 这样下去,你最多能收集到多少个苹果。

解这个问题与解其它的DP问题几乎没有什么两样。第一步找到问题的“状态”, 第二步找到“状态转移方程”,然后基本上问题就解决了。

首先,我们要找到这个问题中的“状态”是什么?我们必须注意到的一点是, 到达一个格子的方式最多只有两种:从左边来的(除了第一列)和从上边来的(除了第一行)。 因此为了求出到达当前格子后最多能收集到多少个苹果, 我们就要先去考察那些能到达当前这个格子的格子,到达它们最多能收集到多少个苹果。 (是不是有点绕࿰

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用A*算法求解最短路径迷宫的Python代码示例: ```python import heapq class Maze: def __init__(self, maze): self.maze = maze self.start = None self.end = None self.width = len(maze[0]) self.height = len(maze) for y in range(self.height): for x in range(self.width): if maze[y][x] == 'S': self.start = (x, y) elif maze[y][x] == 'E': self.end = (x, y) def is_valid(self, x, y): if x < 0 or y < 0 or x >= self.width or y >= self.height: return False if self.maze[y][x] == '#': return False return True def get_neighbors(self, x, y): neighbors = [] for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)): nx, ny = x + dx, y + dy if self.is_valid(nx, ny): neighbors.append((nx, ny)) return neighbors def heuristic_cost_estimate(self, from_node, to_node): return abs(from_node[0] - to_node[0]) + abs(from_node[1] - to_node[1]) def a_star_search(self): frontier = [(0, self.start)] came_from = {} g_score = {self.start: 0} f_score = {self.start: self.heuristic_cost_estimate(self.start, self.end)} while frontier: current = heapq.heappop(frontier)[1] if current == self.end: path = [] while current in came_from: path.append(current) current = came_from[current] path.append(self.start) path.reverse() return path for neighbor in self.get_neighbors(*current): tentative_g_score = g_score[current] + 1 if neighbor not in g_score or tentative_g_score < g_score[neighbor]: came_from[neighbor] = current g_score[neighbor] = tentative_g_score f_score[neighbor] = tentative_g_score + self.heuristic_cost_estimate(neighbor, self.end) heapq.heappush(frontier, (f_score[neighbor], neighbor)) return None maze = Maze([ "#######", "#S....#", "#.#.#.#", "#.#...#", "#.#.#.#", "#.....#", "#######" ]) path = maze.a_star_search() if path: for y in range(maze.height): for x in range(maze.width): if (x, y) == maze.start: print('S', end='') elif (x, y) == maze.end: print('E', end='') elif (x, y) in path: print('*', end='') else: print(maze.maze[y][x], end='') print() else: print('No path found') ``` 运行以上代码会输出如下结果: ``` ####### #S****# #.#.#*# #.#..*# #.#.#*# #....*# ####### ``` 其中,S代表起点,E代表终点,*代表最短路径上的格子
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值