![[백준 C++] 1679 : 숨바꼭질](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fc4bPOl%2FbtsKNW5SYvC%2FvDmcubfekhghwwtOreks7k%2Fimg.png)
[백준 C++] 1679 : 숨바꼭질CSE/코딩 문제풀이2024. 11. 18. 17:01
Table of Contents
https://www.acmicpc.net/problem/1697
이전글에 풀었던 미로 탐색에서 사용하였던 방법을 응용하면 되는 문제이다.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> list;
vector<bool> visited;
vector<int> answer;
void bfs(int start)
{
int size = list.size();
queue<int> que;
que.push(start);
visited[start] = true;
while (!que.empty())
{
int current = que.front();
que.pop();
if (current - 1 >= 0)
{
if (!visited[current - 1])
{
que.push(current - 1);
visited[current - 1] = true;
answer[current - 1] = answer[current] + 1;
}
}
if (current + 1 < size)
{
if (!visited[current + 1])
{
que.push(current + 1);
visited[current + 1] = true;
answer[current + 1] = answer[current] + 1;
}
}
if (current * 2 < size)
{
if (!visited[current * 2])
{
que.push(current * 2);
visited[current * 2] = true;
answer[current * 2] = answer[current] + 1;
}
}
}
}
int main()
{
int N, K;
cin >> N >> K;
list = vector<int>(((N > K ? N : K) + 1) * 2, 0);
visited = vector<bool>(((N > K ? N : K) + 1) * 2, false);
answer = vector<int>(((N > K ? N : K) + 1) * 2, 0);
bfs(N);
cout << answer[K] << '\n';
return 0;
}
더 정확하게 계산하면 배열의 크기가 줄어들 수 있겠지만, 간단하게 N과 K중 큰 수 이전에 * 2를 할 수 있다고 생각하여 배열의 크기를 ((N > K ? N : K) + 1) * 2 로 설정하였다.
한번 방문한 곳은 이전 방문한 곳의 개수에 +1로 해주어 answer에 저장하는 방식으로 구현하였다.
'CSE > 코딩 문제풀이' 카테고리의 다른 글
[백준 C++] 11866 : 요세푸스 문제 0 (0) | 2024.11.20 |
---|---|
[백준 C++] 7562 : 나이트의 이동 (0) | 2024.11.19 |
[백준 C++] 2178 : 미로 탐색 (0) | 2024.11.17 |
[백준 C++] 1012 : 유기농 배추 (2) | 2024.11.16 |
[백준 C++] 2667 : 단지번호붙이기 (0) | 2024.11.15 |
@NiffJB :: 개발하는 니프
CSE & GAME 개발 블로그
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 부탁드립니다!