Graph: Enhance path finiding
This commit is contained in:
@@ -54,22 +54,25 @@ namespace PamhagenSysCtrl.Helpers.Pipeline {
|
|||||||
return p;
|
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");
|
if (!Nodes.Contains(start) || !Nodes.Contains(end)) throw new ArgumentException("Start/end node not contained in graph");
|
||||||
valid ??= a => true;
|
valid ??= a => true;
|
||||||
|
visited ??= [];
|
||||||
|
visited.Add(start);
|
||||||
List<(IEdge, INode)> hops = [];
|
List<(IEdge, INode)> hops = [];
|
||||||
Path? path = null;
|
Path? path = null;
|
||||||
foreach (var o in start.Outputs) {
|
foreach (var o in start.Outputs) {
|
||||||
if (o.End == end) {
|
var e = o.IsTwoWay && o.End == start ? o.Start : o.End;
|
||||||
return new(start, [(o, o.End)]);
|
if (e == end) {
|
||||||
} else if (!valid(o.End) || (!o.IsTwoWay && o.End == start) || (o.IsTwoWay && o.End == start)) {
|
return new(start, [(o, e)]);
|
||||||
|
} else if (!valid(e) || visited.Contains(e)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var p = GetPath(o.End, end, valid);
|
var p = GetPath(e, end, valid, visited);
|
||||||
if (p != null) {
|
if (p != null) {
|
||||||
var p2 = new Path(start, [(o, o.End), .. p.Value.Hops]);
|
var p2 = new Path(start, [(o, e), .. p.Value.Hops]);
|
||||||
if (path == null || p2.Length < path.Value.Length) {
|
if (path == null || p2.Bends < path.Value.Bends || (p2.Bends == path.Value.Bends && p2.Length < path.Value.Length)) {
|
||||||
path = p2;
|
path = p2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
INode Start,
|
INode Start,
|
||||||
IEnumerable<(IEdge Edge, INode Node)> Hops)
|
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));
|
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