Skip to content

Commit d413d06

Browse files
authoredNov 1, 2021
Update 1263-minimum-moves-to-move-a-box-to-their-target-location.js
1 parent 323b9dc commit d413d06

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
 

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

+83
Original file line numberDiff line numberDiff line change
@@ -281,3 +281,86 @@ const minPushBox = function (grid) {
281281
}
282282
}
283283

284+
// another
285+
286+
/**
287+
* @param {character[][]} grid
288+
* @return {number}
289+
*/
290+
const minPushBox = function (grid) {
291+
const m = grid.length,
292+
n = grid[0].length
293+
let target, person, box
294+
for (let i = 0; i < m; i++) {
295+
for (let j = 0; j < n; j++) {
296+
if (grid[i][j] === 'T') target = [i, j]
297+
else if (grid[i][j] === 'B') box = [i, j]
298+
else if (grid[i][j] === 'S') person = [i, j]
299+
}
300+
}
301+
302+
const valid = ([x, y]) => {
303+
return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] !== '#'
304+
}
305+
306+
const check = (cur, dest, box) => {
307+
const q = [cur]
308+
const visited = new Set([`${box[0]},${box[1]}`])
309+
const dirs = [
310+
[-1, 0],
311+
[1, 0],
312+
[0, 1],
313+
[0, -1],
314+
]
315+
316+
while (q.length) {
317+
const pos = q.shift()
318+
if (pos.join(',') === dest.join(',')) return true
319+
const newPos = []
320+
for (const [dx, dy] of dirs) newPos.push([pos[0] + dx, pos[1] + dy])
321+
for (const [nx, ny] of newPos) {
322+
const k = `${nx},${ny}`
323+
if (valid([nx, ny]) && !visited.has(k)) {
324+
visited.add(k)
325+
q.push([nx, ny])
326+
}
327+
}
328+
}
329+
330+
return false
331+
}
332+
333+
const q = [[0, box, person]]
334+
const vis = new Set([`${box.join(',')},${person.join(',')}`])
335+
while (q.length) {
336+
const [dist, box, person] = q.shift()
337+
if (box.join(',') === target.join(',')) return dist
338+
339+
const bCoord = [
340+
[box[0] + 1, box[1]],
341+
[box[0] - 1, box[1]],
342+
[box[0], box[1] + 1],
343+
[box[0], box[1] - 1],
344+
]
345+
const pCoord = [
346+
[box[0] - 1, box[1]],
347+
[box[0] + 1, box[1]],
348+
[box[0], box[1] - 1],
349+
[box[0], box[1] + 1],
350+
]
351+
352+
for (let i = 0; i < 4; i++) {
353+
const [newBox, newPerson] = [bCoord[i], pCoord[i]]
354+
const key = `${newBox.join(',')},${box.join(',')}`
355+
if (valid(newBox) && !vis.has(key)) {
356+
if (valid(newPerson) && check(person, newPerson, box)) {
357+
vis.add(key)
358+
q.push([dist + 1, newBox, box])
359+
}
360+
}
361+
}
362+
}
363+
364+
return -1
365+
}
366+

0 commit comments

Comments
 (0)
Please sign in to comment.