我已經實現了根據維基百科實現的A *算法here 但是,它在移動設備中運行速度太慢。我必須等待無盡的時間來完成這項功能,儘管它在臺式電腦上運行良好。我能做些什麼來優化算法?優化A-Star算法
下面是實際的代碼
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;
}
你有沒有簡介?什麼似乎是瓶頸? – Oded 2010-08-08 19:12:28
看來Dictionary類和getLowestFscore()是瓶頸。 getLowestFscore只是一個找到最低FScore的for循環。我應該用什麼替換它們? – VOX 2010-08-08 19:15:23
好像你有太多的數據讓你的移動設備來處理它。你有多少個節點?也許你應該把你在字典中使用的數據降到最低。 – MicSim 2010-08-08 19:27:25