AcWing 845. 八数码
原题链接
中等
作者:
yennywang
,
2024-11-07 10:24:27
,
所有人可见
,
阅读 1
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let q = []
let dis_map = new Map()
// map get delete set has
let directions = [[0, -1], [0, 1], [-1, 0], [1, 0]] //上下左右
rl.on('line', line => {
// 初始化状态
q.push(line.split(' ').join(''))
dis_map.set(q[0], 0);
})
rl.on('close', line => {
let res
while(q.length > 0){
let t = q.shift()
if(t == '12345678x') res = dis_map.get(t)
const index = t.indexOf('x')
const x = Math.floor(index / 3), y = index % 3
directions.map(d => {
const nx = x + d[0], ny = y + d[1] //下一个移动位置
if(nx >= 0 && ny >= 0 && nx < 3 && ny < 3){
let newPath = [...t]
let tmp = newPath[nx*3+ny]
newPath[nx*3+ny] = newPath[x*3+y]
newPath[x*3+y] = tmp
newPath = newPath.join('')
if(!dis_map.has(newPath)){
dis_map.set(newPath, dis_map.get(t)+1)
q.push(newPath)
}
}
})
}
console.log(res >= 0 ? res : -1)
})