Coding Test - cpp/BFS
[백준 1697: 숨바꼭질] - C++
에드윈H
2021. 1. 14. 13:28
#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
int N, K;
int disArr[100001];
int NextLocation(int index, int number) {
switch (index) {
case 0:
return -1 + number;
case 1:
return 1 + number;
case 2:
return 2 * number;
}
}
int main()
{
cin >> N >> K;
if (N == K) { //위치 같을 경우 바로 종료
cout << 0 << endl;
return 0;
}
queue<int> Q;
disArr[N] = 0;
Q.push(N);
int curX;
int nextX;
while (!Q.empty())
{
curX = Q.front();
Q.pop();
for (int i = 0; i < 3; i++)
{
nextX = NextLocation(i, curX);
if (nextX < 0 || 100000 < nextX)
continue;
if (nextX == K) //찾았을 경우
{
cout << disArr[curX] + 1 << endl;
return 0;
}
if (disArr[nextX] == 0)
{
disArr[nextX] = disArr[curX] + 1;
Q.push(nextX);
}
}
}
return 0;
}