Graph: Enhance path finiding

This commit is contained in:
2026-07-14 12:31:42 +02:00
parent 6e49693db4
commit da257b3285
2 changed files with 11 additions and 7 deletions
+10 -7
View File
@@ -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;
}
}
+1
View File
@@ -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));
}
}