본문 바로가기

백준/C++

[C++] 백준 1697번 - 숨바꼭질

728x90

 

으... 너무 졸리다...

 

문제 1697번

https://www.acmicpc.net/problem/1697

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

 

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int n, k;
bool visited[100001];

void bfs(int n) {
	queue<pair<int, int>> q;
	q.push({ n,0 });
	while (!q.empty()) {
		int x = q.front().first;
		int cnt = q.front().second;
        	q.pop();
		if (x == k) {
			cout << cnt << endl;
			break;
		}
		if (0 <= x - 1 && x - 1 <= 100000) {
			if (!visited[x - 1]) {
				visited[x - 1] = true;
				q.push({ x - 1,cnt + 1 });
			}
		}
		if (0 <= x + 1 && x + 1 <= 100000) {
			if (!visited[x + 1]) {
				visited[x + 1] = true;
				q.push({ x + 1,cnt + 1 });
			}
		}
		if (0 <= x * 2 && x * 2 <= 100000) {
			if (!visited[x * 2]) {
				visited[x * 2] = true;
				q.push({ x * 2,cnt + 1 });
			}
		}
	}
}

int main(void) {
	cin >> n >> k;
	visited[n] = true;
	bfs(n);
}

 

 

 

728x90

'백준 > C++' 카테고리의 다른 글

[C++] 백준 10773번 - 제로  (2) 2024.03.24
[C++] 백준 4963번 - 섬의 개수  (2) 2024.03.22
[C++] 백준 2178번 - 미로 탐색  (0) 2024.03.07
[C++] 백준 2606번 - 바이러스  (3) 2024.03.05
[C++] 백준 1260번 - DFS와 BFS  (2) 2024.03.04