forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0286-walls-and-gates.kt
30 lines (29 loc) · 1.09 KB
/
0286-walls-and-gates.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
class Solution {
fun wallsAndGates(rooms: Array<IntArray>): Unit {
val queue: Queue<Pair<Int, Int>> = LinkedList()
for (i in 0 until rooms.size) {
for (j in 0 until rooms[0].size) {
if (rooms[i][j] == 0) {
queue.offer(Pair(i, j))
}
}
}
val directions = arrayOf(arrayOf(-1, 0), arrayOf(1, 0), arrayOf(0, -1), arrayOf(0, 1))
var distance = 1
while (queue.isNotEmpty()) {
val size = queue.size
repeat(size) {
val cell = queue.poll()
for (direction in directions) {
val newRow = cell.first+direction[0]
val newCol = cell.second+direction[1]
if (newRow >= 0 && newRow < rooms.size && newCol >= 0 && newCol < rooms[0].size && rooms[newRow][newCol] == Integer.MAX_VALUE) {
rooms[newRow][newCol] = distance
queue.offer(Pair(newRow, newCol))
}
}
}
distance++
}
}
}