【发布时间】:2015-01-13 08:59:29
【问题描述】:
我正在开发一款带有 2D 阵列(游戏板)的新游戏。每个单元格/图块都有一定数量的点。
我想要实现的是一个算法可以找到具有最高核心的最短路径。
所以我首先实现了 Dijkstra 算法(下面的源代码)来找到从开始到结束的最短路径(红色路线)。这很好用。
我的问题是:我怎样才能扩展我的算法,以便它确定具有最高分数的最短路径(所以绿色路线)。
提前谢谢你!
class Graph
{
// Dictionary<Start Point, vertices>
Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>();
public void add_vertex(char name, Dictionary<char, int> edges)
{
vertices[name] = edges;
}
public List<char> shortest_path(char start, char finish)
{
var previous = new Dictionary<char, char>();
var distances = new Dictionary<char, int>();
var nodes = new List<char>();
List<char> path = null;
foreach (var vertex in vertices)
{
if (vertex.Key == start)
{
distances[vertex.Key] = 0;
}
else
{
distances[vertex.Key] = int.MaxValue;
}
nodes.Add(vertex.Key);
}
while (nodes.Count != 0)
{
nodes.Sort((x, y) => distances[x] - distances[y]);
var smallest = nodes[0];
nodes.Remove(smallest);
if (smallest == finish)
{
path = new List<char>();
while (previous.ContainsKey(smallest))
{
path.Add(smallest);
smallest = previous[smallest];
}
break;
}
if (distances[smallest] == int.MaxValue)
{
break;
}
foreach (var neighbor in vertices[smallest])
{
var alt = distances[smallest] + neighbor.Value;
if (alt < distances[neighbor.Key])
{
distances[neighbor.Key] = alt;
previous[neighbor.Key] = smallest;
}
}
}
return path;
}
}
更新:
我已经尝试过类似的方法,但似乎不起作用:
foreach (var neighbour in _vertices[smallest])
{
// The variable alt is the length of the path from the root node to the neighbor node if it were to go through _vertices[smallest].
var alt = pointInfos[smallest].Distance + neighbour.Value.Distance;
var altScore = pointInfos[smallest].Points + neighbour.Value.Points;
if (alt <= pointInfos[neighbour.Key].Distance && altScore > pointInfos[neighbour.Key].Points) // A shorter path with higher points to neighbour has been found
{
pointInfos[neighbour.Key] = new PointInfo(alt, altScore);
previous[neighbour.Key] = smallest;
}
}
【问题讨论】:
-
你的绿色路径不是最短的。
-
没错:是最短路径,得分最高!这就是我想要实现的目标......
-
当您有两个条件时,您必须正确地订购它们。你是说要先获得最高分,然后如果两条路径得分相同,则选择最短的?