Minimum Knight Moves
Description
null
Solution(javascript)
/**
* @param {number} x
* @param {number} y
* @return {number}
*/
const minKnightMoves = function (x, y) {
let moves = 0
let current = [[0, 0]]
const visited = {
'0-0': true,
}
const isValid = (x1, y1) => Math.abs(x1) + Math.abs(y1) <= 300
while (current.length > 0) {
const next = []
const push = (x2, y2) => {
const key = `${x2}-${y2}`
if (isValid(x2, y2) && !visited[key]) {
visited[key] = true // 加的时候就设置这个,避免加入重复的
next.push([x2, y2])
}
}
for (const [x1, y1] of Object.values(current)) {
if (x1 === x && y1 === y) {
return moves
}
push(x1 + 1, y1 + 2)
push(x1 + 2, y1 + 1)
push(x1 + 2, y1 - 1)
push(x1 + 1, y1 - 2)
push(x1 - 1, y1 - 2)
push(x1 - 2, y1 - 1)
push(x1 - 2, y1 + 1)
push(x1 - 1, y1 + 2)
}
moves += 1
current = next
}
return moves
}