【发布时间】:2011-03-27 00:39:05
【问题描述】:
根据维基百科在here 的实现,我已经实现了 A* 算法 但是,在移动设备上运行太慢了。尽管它在台式计算机上运行良好,但我必须等待无数小时才能完成该功能。有什么办法可以优化算法吗?
这是实际代码
public DriveRoute findroute(routenode from, routenode to)
{
Dictionary<int, routenode> openlist = new Dictionary<int, routenode>();
openlist.Add(from.nodeid, from);
Dictionary<int, routenode> closedlist = new Dictionary<int, routenode>();
Dictionary<int, double> gscores = new Dictionary<int, double>();
gscores.Add(from.nodeid, 0);
Dictionary<int, double> hscores = new Dictionary<int, double>();
hscores.Add(from.nodeid, distanceForRouting(from.latlon, to.latlon));
Dictionary<int, double> fscores = new Dictionary<int, double>();
fscores.Add(from.nodeid, gscores[from.nodeid] + hscores[from.nodeid]);
Dictionary<int, routenode> came_from = new Dictionary<int, routenode>();
while (openlist.Values.Count > 0)
{
routenode x = getLowestFscore(openlist, fscores);
if (x.latlon.Equals(to.latlon))
{
return rebuildPathWay(came_from, to);
}
openlist.Remove(x.nodeid);
closedlist.Add(x.nodeid, x);
foreach (routearc arc in x.outgoingarcs)
{
if (closedlist.Keys.Contains(arc.endnode))
continue;
double tentative_g_score = gscores[x.nodeid] + arc.time;
bool tentative_is_better = false;
if (!openlist.Keys.Contains(arc.endnode))
{
openlist.Add(arc.endnode, map.routenodes[arc.endnode]);
tentative_is_better = true;
}
else if (tentative_g_score < gscores[arc.endnode])
{
tentative_is_better = true;
}
if (tentative_is_better)
{
if (came_from.ContainsKey(arc.endnode))
came_from[arc.endnode] = x;
else
came_from.Add(arc.endnode, x);
gscores[arc.endnode] = tentative_g_score;
hscores[arc.endnode] = distanceForRouting(arc.endlatlon, to.latlon);
fscores[arc.endnode] = gscores[arc.endnode] + hscores[arc.endnode];
}
}
}
return null;
}
【问题讨论】:
-
你分析过它吗?瓶颈似乎是什么?
-
似乎 Dictionary 类和 getLowestFscore() 是瓶颈。 getLowestFscore 只是一个用于查找最低 FScore 的 for 循环。我应该用什么替换它们?
-
您的移动设备似乎有太多数据无法处理。你有多少个节点?也许您应该将您在字典中使用的数据分解到最低限度。
-
30,000!即使算法是线性的......
标签: c# routing navigation gps