Skip to content

Instantly share code, notes, and snippets.

@fengyitsai
Created February 13, 2020 17:47
Show Gist options
  • Save fengyitsai/2d10563bb75145b18b7d15fc4cdc27df to your computer and use it in GitHub Desktop.
Save fengyitsai/2d10563bb75145b18b7d15fc4cdc27df to your computer and use it in GitHub Desktop.
1091. Shortest Path in Binary Matrix
class Solution {
func shortestPathBinaryMatrix(_ grid: [[Int]]) -> Int {
guard !grid.isEmpty, !grid[0].isEmpty else {
return -1
}
var visited = grid
var step = 1
var queue = [(0,0)]
if visited[0][0] == 1 {
return -1
} else {
visited[0][0] = 1
}
while !queue.isEmpty {
var nextQueue = [(Int,Int)]()
for point in queue {
if point == (grid.count-1,grid[0].count-1) {
return step
}
let vectors = [(0,-1),(0,1),(1,-1),(1,1),(1,0),(-1,-1),(-1,1),(-1,0)]
for vector in vectors {
let nextPoint = (point.0+vector.0, point.1+vector.1)
guard nextPoint.0 >= 0, nextPoint.0 < grid.count, nextPoint.1 >= 0, nextPoint.1 < grid[0].count else {
continue
}
guard visited[nextPoint.0][nextPoint.1] == 0 else {
continue
}
nextQueue.append(nextPoint)
visited[nextPoint.0][nextPoint.1] = 1
}
}
step += 1
queue = nextQueue
}
return -1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment