-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind-calf.js
42 lines (38 loc) ยท 1.13 KB
/
find-calf.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
/**
* @desc problem : ์ก์์ง ์ฐพ๊ธฐ (BFS)
* @desc site : Olympiad
* @desc level: 3
* @desc solution : BFS
*/
/**
* solution
* @param position {number} ํ์ฌ ์์น
* @param calfPosition {number} ์ก์์ง ์์น
*/
const solution = (position, calfPosition) => {
let answer = 0;
const checkArray = Array.from({ length: 10 }, () => 0);
const disposition = Array.from({ length: 10 }, () => 0);
const queue = [];
checkArray[position] = 1;
queue.push(position);
disposition[position] = 0;
while (queue.length) {
const node = queue.shift();
//๋ค์ ์ด๋๊ฑฐ๋ฆฌ๋ -1, +1, +5 ๊ฒฝ์ฐ์ ์๊ฐ ์กด์ฌ
for (let nextNode of [node - 1, node + 1, node + 5]) {
//์ก์์ง ์์น๋ฅผ ๋ฐ๊ฒฌํ์ ๋ (ํ์ ์ข
๋ฃ)
if (nextNode === calfPosition) {
return disposition[node] + 1;
}
//์๋ก์ด ๋
ธ๋ ํ์
if (nextNode > 0 && nextNode < 10000 && checkArray[nextNode] === 0) {
checkArray[nextNode] = 1; //๋ฐฉ๋ฌธ ์ง์ ํ์
queue.push(nextNode);
disposition[nextNode] = disposition[node] + 1;
}
}
}
return answer;
};
console.log(solution(5, 14));