Graph
public protocol Graph
This protocol declares the requirements for optimal pathfinding in a directed graph of nodes and implements the A* algorithm via an extension.
-
The type for the nodes or points in the graph
Declaration
Swift
associatedtype Node : Hashable
-
The endpoints of all edges that start from a certain reference node
Parameters
nodeThe reference node
-
The estimated/heuristic cost to reach the indicated end node from a given start node
The way you implement the estimation of the cost will impact the efficiency of the path finding algorithm.
Admissibility:
When the
estimatedCostnever overestimates the actual cost, thefindPath(from:to:)method will find the optimal path.Monotonicity
When the
estimatedCostis a monotone decreasing funciton, thefindPath(from:to:)method is guaranteed to find an optimal path without processing any node more than once. The function is said to be monotone decreasing whenestimatedCost(from: start, to: end) <= cost(from: start, to: intermediate) + estimatedCost(from: intermediate, to: end)for every edge (start,intermediate).Parameters
startthe starting point of the path who’s cost is to be estimated
endthe end point of the path who’s cost is to be estimated
-
The actual cost to reach the indicated end node from a given start node
Parameters
startthe starting point of the path who’s cost is to be estimated
endthe end point of the path who’s cost is to be estimated
-
findPath(from:Extension methodto: ) Attempts to find the optimal path from a reference node to the indicated goal node. If such a path exists, it is returned in start to end order. If it doesn’t exist, the returned array will be empty.
Parameters
startNodethe start node of the pathfinding attempt
goalNodethe goal node of the pathfinding attempt
Return Value
An optimal path between start and goal if it exists, otherwise an empty array.
View on GitHub
Graph Protocol Reference