https://www.acmicpc.net/problem/11060
11060번: 점프 점프
재환이가 1×N 크기의 미로에 갇혀있다. 미로는 1×1 크기의 칸으로 이루어져 있고, 각 칸에는 정수가 하나 쓰여 있다. i번째 칸에 쓰여 있는 수를 Ai라고 했을 때, 재환이는 Ai이하만큼 오른쪽으로
www.acmicpc.net
풀이법
1) 방문한 곳을 체크하는 visited배열과 BFS기반의 알고리즘으로 문제를 해결했다.
2) i번째 index에 있는 값 이하로 점프할 수 있기에 for문을 1부터 arr[index]까지 값으로 돌려 모든 경우의 수를 bfs 기반의 알고리즘으로 탐색하여 문제를 해결하였다.
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
#define INF 987654321
using namespace std;
int n;
int arr[1001];
bool visited[1001];
void bfs(int start)
{
queue<pair<int, int>> q;
visited[1] = true;
q.push({ 1,0 });
while (!q.empty())
{
int nowIndex = q.front().first;
int cnt = q.front().second;
q.pop();
if (nowIndex == n)
{
cout << cnt;
return;
}
for (int i = 1; i <= arr[nowIndex]; i++)
{
if (!visited[nowIndex+i]&& nowIndex+i<=n)
{
visited[nowIndex+i] = true;
q.push({ nowIndex+i,cnt + 1 });
}
}
}
cout << -1;
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++)
cin >> arr[i];
bfs(1);
}
'Coding_Test_C++' 카테고리의 다른 글
BaekJoon 14442번: 벽 부수고 이동하기 2(C++) (0) | 2021.08.02 |
---|---|
BaekJoon 14923번: 미로 탈출(C++) (0) | 2021.08.01 |
BaekJoon 11403번: 경로 찾기(C++) (0) | 2021.07.31 |
BaekJoon 13901번: 로봇(C++) (0) | 2021.07.30 |
BaekJoon 9372번: 상근이의 여행(C++) (0) | 2021.07.29 |