코드
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
void BFS(int _City,int _Start, int _k,std::map<int, std::vector<int>>& _Map)
{
std::vector<int> Result;
std::vector<bool> Visited;
Visited.resize(_City);
std::queue<std::pair<int, int>> Q;
Q.push(std::make_pair(_Start, 0));
Visited[_Start-1] = true;
while (!Q.empty())
{
int Value = Q.front().first;
int Count = Q.front().second;
Q.pop();
if (Count == _k)
{
Result.push_back(Value);
}
for (int i = 0; i < _Map[Value].size(); i++)
{
int Next = _Map[Value][i];
if (false == Visited[Next - 1])
{
Visited[Next - 1] = true;
Q.push(std::make_pair(Next, Count + 1));
}
}
}
if (Result.size() == 0)
{
std::cout << -1 << "\n";
}
else
{
std::sort(Result.begin(), Result.end());
for (int i = 0; i < Result.size(); i++)
{
std::cout << Result[i] << "\n";
}
}
}
int main()
{
std::map<int, std::vector<int>> Map;
int N, M, K, X;
std::cin >> N >> M >> K >> X;
for (int i = 0; i < M; i++)
{
int A, B;
std::cin >> A >> B;
Map[A].push_back(B);
}
BFS(N,X, K, Map);
return 0;
}