코테/백준 문제풀이

백준 1697 숨바꼭질

밤밭황제 2021. 8. 12. 15:28
#include <iostream>
#include <queue>
#include<algorithm>

using namespace std;
queue<pair<int, int>> q;
bool visited[100001];
int result;
bool valid(int n) {
	if (n < 0 || n > 100000 || visited[n])
		return false;
	return true;
}

int BFS(int end)
{
	while (!q.empty())
	{
		int r = q.front().first;
		int l = q.front().second;
		q.pop();

		if (r == end)
			return l;
			
			if (valid(r*2))
			{
				visited[r * 2] = true;
				q.push(make_pair(r*2, l + 1));
				
			}
			if (valid(r +1))
			{
				visited[r + 1] = true;
				q.push(make_pair(r+1, l + 1));
			}
			if (valid(r-1))
			{
				visited[r- 1] = true;
				q.push(make_pair(r -1, l + 1));
			}
		}
		
	}

int main()
{
	int start, end;
	scanf("%d %d", &start, &end);	
	
	q.push( make_pair(start, 0));
	visited[start] = true;
	printf("%d", BFS(end));

	return 0;
}
728x90