Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function knight(start, finish) {
- console.log(start, finish)
- const s = getCoords(start)
- const f = getCoords(finish)
- return getShortestPath(s.x, s.y, f.x, f.y, new Set(), 0)
- }
- function getShortestPath(startX, startY, targetX, targetY, visited, len) {
- if (startX === targetX && startY === targetY) {
- return len
- }
- visited.add(`${startX}:${startY}`)
- const paths = [...getPaths(startX, startY)]
- .filter(p => isInBounds(p) && !visited.has(`${p.x}:${p.y}`))
- .map(p => getShortestPath(p.x, p.y, targetX, targetY, visited, len + 1))
- .filter(x => !Number.isNaN(x))
- return paths.length > 0 ? Math.min(...paths) : NaN
- }
- function getCoords(str) {
- return {
- x: 'abcdefgh'.indexOf(str[0]),
- y: Number(str[1]) - 1
- }
- }
- function* getPaths(x, y) {
- yield {x: x+2, y: y+1}
- yield {x: x+2, y: y-1}
- yield {x: x-2, y: y+1}
- yield {x: x-2, y: y-1}
- yield {x: x+1, y: y+2}
- yield {x: x+1, y: y-2}
- yield {x: x-1, y: y+2}
- yield {x: x-1, y: y-2}
- }
- function isInBounds(p) {
- return p.x >= 0 && p.x < 8 && p.y >= 0 && p.y < 8
- }
Advertisement
Add Comment
Please, Sign In to add comment