
문제

https://www.acmicpc.net/problem/1697
1697번: 숨바꼭질
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일
www.acmicpc.net
문제 풀이
이 문제는 1초씩 움직이며 동생에게 도착하는 최소 시간을 구하는 문제이므로 BFS를 사용해보았다. 수빈이는 1초마다 +1 , -1 , X2로 세가지 방법으로 움직일 수 있다. 이 때 위치는 0 <= Point <= 100,000임을 참고하여 범위를 초과하면 queue에 넣지 않는다.
더해서 visit 배열에 방문한 점은 표시를 하여 중복으로 수행하는 것을 방지한다.
const fs = require('fs');
const stdin = (process.platform === 'linux'? fs.readFileSync('/dev/stdin').toString() :
`5 17`).split('\n');
const input = (() => {
let line = 0;
return () => stdin[line++];
})();
function solution(){
const [N, K] = input().split(" ").map(Number);
const visit = Array.from({ length: 100100 }, () => 0);
function bfs(N) {
const queue = [];
queue.push([N, 0]);
visit[N] = 1;
while (queue.length) {
const [cur, time] = queue.shift();
if (cur === K) return time;
for (next of [cur - 1, cur + 1, cur * 2]) {
if (!visit[next] && next >= 0 && next <= 100000) {
visit[next] = 1;
queue.push([next, time + 1]);
}
}
}
}
console.log(bfs(N));
}
solution();
'algorithm > problems' 카테고리의 다른 글
| [백준] 14225번 부분수열의 합 _ Node.js (0) | 2022.11.13 |
|---|---|
| [백준] 14226번 이모티콘 - Node.js (0) | 2022.11.13 |
| [백준] 15988번 1, 2, 3 더하기 3 (0) | 2022.11.07 |
| [백준] 2178번 미로 탐색 (0) | 2022.11.07 |
| [백준] 14888번 연산자 끼워넣기 (0) | 2022.11.07 |