由N个点和N-1条边构成的有向图中,求从一个点是否能走到其余所有的点?
#include <iostream>
#include <vector>
using namespace std;
int n, m;
vector<int> adj[101];
bool visited[101];
void dfs(int u) {
if (visited[u]) {
return;
}
visited[u] = true;
for (auto v: adj[u]) {
dfs(v);
}
}
int main() {
cin >> n;
m = n - 1;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
adj[v].push_back(u); // reversed
}
for (int i = 1; i <= n; i++) {
dfs(i);
int cnt = 0;
for (int j = 1; j <= n; j++) {
if (visited[j]) {
cnt++;
visited[j] = false;
}
}
if (cnt == n) {
cout << i << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}
网友评论