Created
February 13, 2016 04:30
-
-
Save zntfdr/6682130352b342f9e909 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal func shortestPath(source: Vertex, destination: Vertex) -> Path? { | |
var frontier: [Path] = [] { | |
didSet { | |
frontier.sortInPlace() | |
} | |
} | |
var finalPaths: [Path] = [] { | |
didSet { | |
finalPaths.sortInPlace() | |
} | |
} | |
// the frontier is made by a path that starts nowhere and ends in the source | |
frontier.append(Path(toVertex: source)) | |
while !frontier.isEmpty { | |
let cheapestPathInFrontier = frontier.removeFirst() | |
guard !cheapestPathInFrontier.endVertex.visited else { continue } | |
cheapestPathInFrontier.endVertex.visited = true | |
if (cheapestPathInFrontier.endVertex === destination) { | |
finalPaths.append(cheapestPathInFrontier) | |
continue | |
} | |
for edge in cheapestPathInFrontier.endVertex.edges where !edge.to.visited { | |
let newPath = Path(toVertex: edge.to, viaEdge: edge, viaPath: cheapestPathInFrontier) | |
frontier.append(newPath) | |
} | |
} | |
return finalPaths.first | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment