-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknightTravails.js
79 lines (67 loc) · 1.95 KB
/
knightTravails.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
export function intToLetter(int) {
return String.fromCharCode(int + 96).toUpperCase();
}
export function createBoard() {
let board = new Map();
for (let i = 1; i <= 8; i++) {
for (let j = 1; j <= 8; j++) {
board.set(`${intToLetter(i)}-${j}`, {
x: i,
y: j,
visited: false,
previousMove: null,
});
}
}
return board;
}
function createKnight(board) {
let getPossibleMoves = (x, y) => {
let knightOffsets = [
[x + 2, y + 1],
[x + 2, y - 1],
[x - 2, y + 1],
[x - 2, y - 1],
[x + 1, y + 2],
[x + 1, y - 2],
[x - 1, y + 2],
[x - 1, y - 2],
];
let possibleMoves = [];
knightOffsets.forEach((offset) => {
let move = `${intToLetter(offset[0])}-${offset[1]}`;
if (board.has(move)) possibleMoves.push(move);
});
return possibleMoves;
};
return { getPossibleMoves };
}
export default function knightMoves(start, end) {
let board = createBoard();
let knight = createKnight(board);
let startPosition = `${intToLetter(start[0])}-${start[1]}`;
let endPosition = `${intToLetter(end[0])}-${end[1]}`;
let queue = [startPosition];
while (queue.length > 0) {
let currentMove = queue.shift();
let x = board.get(currentMove).x;
let y = board.get(currentMove).y;
board.get(currentMove).visited = true;
if (currentMove === endPosition) break;
let possibleMoves = knight.getPossibleMoves(x, y);
possibleMoves.forEach((move) => {
if (!board.get(move).visited) {
board.get(move).visited = true;
board.get(move).previousMove = currentMove;
queue.push(move);
}
});
}
let path = [];
let pathMove = endPosition;
while (pathMove !== startPosition) {
path.push(pathMove);
pathMove = board.get(pathMove).previousMove;
}
return path.reverse();
}