更新时间:2022-12-17 10:44:07
有关加权图你有几个选项查找最短路径:
个人 - 我想我会使用BFS在这种情况下 - 但吃豆子开始,直到你发现所有的目标(恶魔位置) - 它会给你从每个妖吃豆子的最短路径。
请注意,如果你只有几恶魔和一个大板,做A *数次(每妖一次)可能是一个更好的解决方案。
每个人都应该大概基准它,看看它实际上是更好的。
Just to enhance my java script skills i am trying to develop a pacman game in js. have a grid of 20 by 20 . This grid has 0's and 1's which indicate if there is a wall or a path . Now I want to develop a algo for the demons to follow the pacman . I am not sure which algorithm should I go for .
So my input to the function will be foo( current position, pacman position,grid, path)
var maze = [ [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0],
[0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0],
[0,1,0,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,0],
[0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,0],
[0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0],
[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0],
[0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,0],
[0,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,0],
[0,1,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0],
[1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,1],
[0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0],
[0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0],
[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0],
[0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0],
[0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,0],
[0,1,0,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,0],
[0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0],
[0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0]];
For unweighted graph you have a several options for finding a shortest path:
Personally - I think I'd use BFS in this case - but start from pacman, until you discover all "targets" (demon locations) - it will give you the shortest path from each demon to pacman.
Note that if you have just a few demons and a big board, doing A* several times (once per demon) might be a better solution.
One should probably benchmark it to see which is actually better.