学习资料:https://www.programmercarl.com/kamacoder/0097.小明逛公园.html
floyd算法,三维矩阵
A*算法
学习记录:
97.小明逛公园(没看懂,抄的)
点击查看代码
# 三维数组Floyd
if __name__ == "__main__":max_int = 10005n,m = map(int, input().split())grid = [[[max_int] * (n+1) for _ in range(n+1)] for _ in range(n+1)]for _ in range(m):p1, p2, w = map(int, input().split())grid[p1][p2][0] = wgrid[p2][p1][0] = wfor k in range(1, n+1):for i in range(1, n+1):for j in range(1, n+1):grid[i][j][k] = min(grid[i][j][k-1], grid[i][k][k-1]+grid[k][j][k-1])z = int(input())for _ in range(z):start, end = map(int, input().split())if grid[start][end][n] == max_int:print(-1)else:print(grid[start][end][n])
127.骑士的攻击(选择欧几里得距离;骑士的走法只有那么8种)
点击查看代码
# 法一:广搜,会超时
# 法二:A* 是有方向性的去搜索;启发式函数;欧拉距离import heapqn = int(input())
moves = [(1,2),(2,1),(-1,2),(2,-1),(1, -2),(-2, 1),(-1,-2),(-2,-1)]def distance(a, b):return ((a[0]-b[0])**2 + (a[1]-b[1])**2) ** 0.5 # 欧式距离def bfs(start, end):q = [(distance(start, end), start)]step = {start:0}while q:d, cur = heapq.heappop(q)if cur == end:return step[cur]for move in moves:new = (move[0]+cur[0], move[1]+cur[1])if 1<=new[0]<=1000 and 1<=new[1]<=1000:step_new = step[cur]+1if step_new<step.get(new, float("inf")):step[new]=step_newheapq.heappush(q, (distance(new, end)+step_new, new))return Falsefor _ in range(n):a1, a2, b1, b2 = map(int, input().split())print(bfs((a1,a2), (b1, b2)))
PS:今天是代码随想录训练营的最后一天,是值得纪念的一天,虽然最后一天依旧没学懂,没关系我还会回来的。
虽然很难,但是也不是珠穆朗玛峰的高度,我相信多练习总能有轻松攀登山顶,俯瞰方圆几百公里风景的那天,加油!
喝到了健康好喝的玉米汁,皮蛋瘦肉粥和担担面都好咸。今天又是工作推进的一天,以后可能就是工地搬砖选手了,希望吃得下这个苦,百炼成钢。