Skip to content

Instantly share code, notes, and snippets.

@leeelton
Created March 3, 2019 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leeelton/948a67a2198f88d9f028983b8a85db52 to your computer and use it in GitHub Desktop.
Save leeelton/948a67a2198f88d9f028983b8a85db52 to your computer and use it in GitHub Desktop.
DFS implementation of the classic maze
struct Pixel {
var color: Color
var isExit: Bool
init(color: Color, isExit: Bool = false) {
self.color = color
self.isExit = isExit
}
}
enum Color {
case white
case black
}
struct Position {
var row: Int
var col: Int
}
func findPath(maze: [[Pixel]], entrance: Position) -> [Position] {
var path: [Position] = []
var visited: [[Bool]] = Array(repeating: Array(repeating: false, count:maze.count), count: maze.count)
path.append(entrance)
visited[entrance.row][entrance.col] = true
if (dfs(maze:maze, curPos:entrance, path:&path, visited:&visited)) {
return path
}
return []
}
func dfs(maze: [[Pixel]], curPos: Position, path: inout [Position], visited: inout [[Bool]]) -> Bool {
if maze[curPos.row][curPos.col].isExit {
return true
} else {
let neighbors = getNeighbors(maze:maze, curPos:curPos)
for neighbor in neighbors {
if !visited[neighbor.row][neighbor.col] {
path.append(neighbor)
visited[neighbor.row][neighbor.col] = true
let foundPath = dfs(maze:maze, curPos:neighbor, path:&path, visited:&visited)
if foundPath {
return true
}
_ = path.removeLast()
visited[neighbor.row][neighbor.col] = false
}
}
return false
}
}
func getNeighbors(maze:[[Pixel]], curPos:Position) -> [Position] {
var neighbors:[Position] = []
// right
if curPos.col + 1 < maze.count && maze[curPos.row][curPos.col+1].color != .black {
neighbors.append(Position(row: curPos.row, col: curPos.col+1))
}
// bottom
if curPos.row + 1 < maze.count && maze[curPos.row+1][curPos.col].color != .black {
neighbors.append(Position(row: curPos.row+1, col: curPos.col))
}
// top
if curPos.row - 1 >= 0 && maze[curPos.row-1][curPos.col].color != .black {
neighbors.append(Position(row: curPos.row - 1, col: curPos.col))
}
// left
if curPos.col - 1 >= 0 && maze[curPos.row][curPos.col-1].color != .black {
neighbors.append(Position(row: curPos.row, col: curPos.col-1))
}
return neighbors
}
var maze: [[Pixel]] = [
[Pixel(color:.white), Pixel(color:.black), Pixel(color:.white)],
[Pixel(color:.white), Pixel(color:.black), Pixel(color:.white)],
[Pixel(color:.white), Pixel(color:.black), Pixel(color:.white, isExit: true)],
]
print(findPath(maze:maze, entrance: Position(row: 0, col: 0)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment