Skip to content

Commit bab4d27

Browse files
authored
Update 1263-minimum-moves-to-move-a-box-to-their-target-location.js
1 parent 6f12355 commit bab4d27

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

1263-minimum-moves-to-move-a-box-to-their-target-location.js

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,99 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {number}
4+
*/
5+
const minPushBox = function (grid) {
6+
let box, person, target
7+
const m = grid.length,
8+
n = grid[0].length
9+
const dirs = [
10+
[-1, 0],
11+
[1, 0],
12+
[0, -1],
13+
[0, 1],
14+
]
15+
for (let i = 0; i < m; i++) {
16+
for (let j = 0; j < n; j++) {
17+
const e = grid[i][j]
18+
if (e === 'B') box = [i, j]
19+
else if (e === 'T') target = [i, j]
20+
else if (e === 'S') person = [i, j]
21+
}
22+
}
23+
24+
const valid = ([i, j]) => {
25+
return i >= 0 && i < m && j >= 0 && j < n && grid[i][j] !== '#'
26+
}
27+
const key = ([i, j]) => `${i},${j}`
28+
29+
const chk = (person, newPerson, box) => {
30+
const set = new Set()
31+
set.add(key(box))
32+
let q = [person]
33+
while (q.length) {
34+
const tmp = []
35+
const size = q.length
36+
for (let i = 0; i < size; i++) {
37+
const [x, y] = q[i]
38+
if (key([x, y]) === key(newPerson)) return true
39+
for (const [dx, dy] of dirs) {
40+
const [nx, ny] = [x + dx, y + dy]
41+
if (valid([nx, ny]) && !set.has(key([nx, ny]))) {
42+
set.add(key([nx, ny]))
43+
tmp.push([nx, ny])
44+
}
45+
}
46+
}
47+
q = tmp
48+
}
49+
return false
50+
}
51+
52+
53+
let q = [[0, box, person]]
54+
const dkey = (a, b) => `${a[0]},${a[1]}_${b[0]},${b[1]}`
55+
const set = new Set()
56+
set.add(dkey(box, person))
57+
while (q.length) {
58+
const size = q.length
59+
const tmp = []
60+
for (let i = 0; i < size; i++) {
61+
const [v, b, p] = q[i]
62+
if (key(b) === key(target)) return v
63+
const bArr = [
64+
[b[0], b[1] + 1],
65+
[b[0], b[1] - 1],
66+
[b[0] + 1, b[1]],
67+
[b[0] - 1, b[1]],
68+
]
69+
const pArr = [
70+
[b[0], b[1] - 1],
71+
[b[0], b[1] + 1],
72+
[b[0] - 1, b[1]],
73+
[b[0] + 1, b[1]],
74+
]
75+
76+
for (let j = 0; j < 4; j++) {
77+
const nb = bArr[j],
78+
np = pArr[j]
79+
const nk = dkey(nb, b)
80+
81+
if (set.has(nk)) continue
82+
if (valid(nb) && valid(np) && chk(p, np, b)) {
83+
tmp.push([v + 1, nb, b])
84+
set.add(nk)
85+
}
86+
}
87+
}
88+
q = tmp
89+
}
90+
91+
return -1
92+
}
93+
94+
// another
95+
96+
197
/**
298
* @param {character[][]} grid
399
* @return {number}

0 commit comments

Comments
 (0)