본문 바로가기
이론/코딩테스트

[백준] 1697번 숨바꼭질 (BFS)

by 퇴근후개발 2022. 7. 30.
반응형

-문제

 

-코드

#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;

int ch[100001];
int cal(int x, int i)
{
	int res=0;
	switch (i)
	{
		case 0:
			res = x - 1;
			break;
		case 1:
			res = x + 1;
			break;
		case 2:
			res = x * 2;
			break;
		default:
			break;
	}
	return res;
}

int main()
{
	int n, k;
	scanf("%d %d", &n, &k);
	queue<int> q;

	if (n == k)
	{
		printf("%d", 0);
		return 0;
	}

	ch[n] = 1;
	q.push(n);
	while (!q.empty())
	{
		int tmp = q.front();
		q.pop();
		//printf("%d : %d\n", tmp, ch[tmp]);
		for (int i = 0; i < 3; i++)
		{
			int pos = cal(tmp, i);
			if (pos < 0 || pos > 100000) continue;
			if (pos == k)
			{
				printf("%d", ch[tmp]);
				return 0;
			}
			if (ch[pos] == 0)
			{
				ch[pos] = ch[tmp] + 1;
				q.push(pos);
			}
		}
	}
	return 0;
}
반응형