Created
March 3, 2019 20:06
-
-
Save leeelton/948a67a2198f88d9f028983b8a85db52 to your computer and use it in GitHub Desktop.
DFS implementation of the classic maze
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
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