Skip to content

Instantly share code, notes, and snippets.

@zntfdr
Created February 13, 2016 04:30
Show Gist options
  • Save zntfdr/6682130352b342f9e909 to your computer and use it in GitHub Desktop.
Save zntfdr/6682130352b342f9e909 to your computer and use it in GitHub Desktop.
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