-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1091-shortest-path-in-binary-matrix.kt
46 lines (39 loc) · 1.27 KB
/
1091-shortest-path-in-binary-matrix.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
fun shortestPathBinaryMatrix(grid: Array<IntArray>): Int {
if(grid[0][0] == 1 || grid[grid.lastIndex][grid.lastIndex] == 1) return -1
fun isValid(i: Int, j: Int) = i in (0..grid.lastIndex) && j in (0..grid.lastIndex) && grid[i][j] == 0
val q = ArrayDeque<Pair<Int, Int>>()
var distance = 0
q.add(0 to 0)
grid[0][0] = 1
while (q.isNotEmpty()) {
distance++
val size = q.size
repeat (size) {
val (i, j) = q.poll()
if(i == grid.lastIndex && j == grid.lastIndex) return distance
for(cell in cells) {
val nextI = i + cell[0]
val nextJ = j + cell[1]
if(isValid(nextI, nextJ)) {
q.add(nextI to nextJ)
grid[nextI][nextJ] = 1
}
}
}
}
return -1
}
companion object {
val cells = arrayOf(
intArrayOf(0,1),
intArrayOf(1,1),
intArrayOf(0,-1),
intArrayOf(1,-1),
intArrayOf(1,0),
intArrayOf(-1,-1),
intArrayOf(-1,0),
intArrayOf(-1, 1)
)
}
}