Graph: Enhance path finiding
This commit is contained in:
@@ -54,22 +54,25 @@ namespace PamhagenSysCtrl.Helpers.Pipeline {
|
||||
return p;
|
||||
}
|
||||
|
||||
public Path? GetPath(INode start, INode end, Func<INode, bool>? valid = null) {
|
||||
public Path? GetPath(INode start, INode end, Func<INode, bool>? valid = null, HashSet<INode>? visited = null) {
|
||||
if (!Nodes.Contains(start) || !Nodes.Contains(end)) throw new ArgumentException("Start/end node not contained in graph");
|
||||
valid ??= a => true;
|
||||
visited ??= [];
|
||||
visited.Add(start);
|
||||
List<(IEdge, INode)> hops = [];
|
||||
Path? path = null;
|
||||
foreach (var o in start.Outputs) {
|
||||
if (o.End == end) {
|
||||
return new(start, [(o, o.End)]);
|
||||
} else if (!valid(o.End) || (!o.IsTwoWay && o.End == start) || (o.IsTwoWay && o.End == start)) {
|
||||
var e = o.IsTwoWay && o.End == start ? o.Start : o.End;
|
||||
if (e == end) {
|
||||
return new(start, [(o, e)]);
|
||||
} else if (!valid(e) || visited.Contains(e)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var p = GetPath(o.End, end, valid);
|
||||
var p = GetPath(e, end, valid, visited);
|
||||
if (p != null) {
|
||||
var p2 = new Path(start, [(o, o.End), .. p.Value.Hops]);
|
||||
if (path == null || p2.Length < path.Value.Length) {
|
||||
var p2 = new Path(start, [(o, e), .. p.Value.Hops]);
|
||||
if (path == null || p2.Bends < path.Value.Bends || (p2.Bends == path.Value.Bends && p2.Length < path.Value.Length)) {
|
||||
path = p2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
INode Start,
|
||||
IEnumerable<(IEdge Edge, INode Node)> Hops)
|
||||
{
|
||||
public readonly double Bends => Hops.Sum(h => h.Edge.Start.CenterX != h.Edge.End.CenterX && h.Edge.Start.CenterY != h.Edge.End.CenterY ? 1 : 0);
|
||||
public readonly double Length => Hops.Sum(h => Math.Abs(h.Edge.Start.CenterX - h.Edge.End.CenterX) + Math.Abs(h.Edge.Start.CenterY - h.Edge.End.CenterY));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user