Last active
July 15, 2020 15:04
-
-
Save BrandonShega/a3ca496400612267113782aa29b00058 to your computer and use it in GitHub Desktop.
Snakes and Ladders
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
class Solution { | |
var moves = 0 | |
var rows = 0 | |
var cols = 0 | |
func snakesAndLadders(_ board: [[Int]]) -> Int { | |
let newBoard = convertTo1D(board) | |
print(newBoard) | |
let n = board.count | |
var queue: [Int] = [] | |
var visited: [Bool] = Array(repeating: false, count: n * n) | |
queue.append(0) | |
visited[0] = true | |
while !queue.isEmpty { | |
var size = queue.count | |
while size > 0 { | |
let square = queue.removeFirst() | |
if square == n * n - 1 { return moves } | |
for var next in square + 1..<min(square + 6, n * n - 1) { | |
let square2 = newBoard[next] | |
if square2 > 0 { next = square2 - 1 } | |
if !visited[next] { | |
visited[next] = true | |
queue.append(next) | |
} | |
} | |
size -= 1 | |
} | |
print(queue) | |
moves += 1 | |
} | |
return -1 | |
} | |
private func convertTo1D(_ board: [[Int]]) -> [Int] { | |
let n = board.count | |
var newBoard: [Int] = [] | |
for row in (0..<n).reversed() { | |
for col in 0..<n { | |
if row % 2 == n % 2 { | |
newBoard.append(board[row][n - col - 1]) | |
} else { | |
newBoard.append(board[row][col]) | |
} | |
} | |
} | |
return newBoard | |
} | |
} | |
let input = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] | |
print(Solution().snakesAndLadders(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment