Pagini recente » Cod sursa (job #2797279) | Cod sursa (job #2465991) | Cod sursa (job #77135) | Cod sursa (job #226630) | Cod sursa (job #1774122)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
int N, M, S;
int const MAX_N = 100001;
bool vis[MAX_N];
int cost[MAX_N];
vector<int> graph[MAX_N];
void BFS(int node, int depth) {
stack<int> st;
vis[node] = true;
st.push(node);
while (!st.empty()) {
int top = st.top();
st.pop();
for (size_t i = 0; i < graph[top].size(); i++) {
int next_node = graph[top][i];
if (!vis[next_node]) {
vis[next_node] = true;
st.push(next_node);
cost[next_node] = cost[top] + 1;
}
}
}
}
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
fin >> N >> M >> S;
for (int i = 0; i < M; i++) {
int n1, n2;
fin >> n1 >> n2;
graph[n1].push_back(n2);
}
BFS(S, 0);
for (int i = 1; i <= N; i++) {
if (vis[i])
fout << cost[i] << " ";
else
fout << -1 << " ";
}
fin.close();
fout.close();
return 0;
}