-
Notifications
You must be signed in to change notification settings - Fork 0
/
286_walls_and_gates.js
42 lines (41 loc) · 1.23 KB
/
286_walls_and_gates.js
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
/**
* @param {number[][]} rooms
* @return {void} Do not return anything, modify rooms in-place instead.
*/
var wallsAndGates = function(rooms) {
// find and start from the gates
let queue = [] // format: [x position, y position, distance]
for (let i=0; i<rooms.length; i++) {
for (let j=0; j<rooms[i].length; j++) {
if (rooms[i][j] === 0) {
queue.push([i, j, 0])
}
}
}
// traverse from the gates
while (queue.length > 0) {
// in each traverse, check the marked value and replace if fewer than the existing distance
// console.log(queue)
let [x, y, d] = queue.shift()
// up
if (x>0 && rooms[x-1][y] > d+1) {
rooms[x-1][y] = d+1
queue.push([x-1, y, d+1])
}
// down
if (x<rooms.length-1 && rooms[x+1][y] > d+1) {
rooms[x+1][y] = d+1
queue.push([x+1, y, d+1])
}
// left
if (y>0 && rooms[x][y-1] > d+1) {
rooms[x][y-1] = d+1
queue.push([x, y-1, d+1])
}
// right
if (y<rooms[0].length-1 && rooms[x][y+1] > d+1) {
rooms[x][y+1] = d+1
queue.push([x, y+1, d+1])
}
}
};