간단한 BFS문제이다. 계산의 편의성을 위해 벡터 크기를 하나씩 더 늘렸다. 범위 지정에 주의해야 한다.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> stone;
vector<bool>visited;
int s, n;
void input_stone()
{
int i, temp;
cin >> n;
visited.resize(n + 1, false);//계산 편하게 하기 위해 배열 크기 하나 더 추가
stone.resize(n + 1, 0);//계산 편하게 하기 위해 배열 크기 하나 더 추가
for (i = 1; i <= n; i++)
{
cin >> stone[i];
}
cin >> s;
return;
}
int BFS(int start)
{
queue <int> q;
int i;
int current, next, count = 0;
vector <int> direction{ 1, -1 };
q.push(start);
visited[start] = true;
count++;
while (!q.empty())
{
current = q.front();
q.pop();
for (i = 0; i < 2; i++)
{
next = current + stone[current] * direction[i];
if (next >= 1 && next <= n && visited[next] == false)
{
//cout << next << "\n";
q.push(next);
visited[next] = true;
count++;
}
}
}
return count;
}
void find_answer()
{
cout << BFS(s) << "\n";
return;
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
input_stone();
find_answer();
return 0;
}