I implemented the A * algorithm. In accordance with the Wikipedia implementation in here , however, on mobile devices it is too slow. I have to wait an infinite clock to finish the function, although it works fine on a desktop computer. Can I do something to optimize the algorithm?
Here is the actual code
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; }
source share