dfs
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110, M = 2010;
int n, m;
int h[N], e[M], ne[M], idx;
bool st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u)
{
st[u] = true;
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j]) dfs(j);
}
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
}
dfs(1);
for (int i = 1; i <= n; i++)
{
if (!st[i])
{
printf("-1\n");
return 0;
}
}
printf("1\n");
}
bfs
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 110, M = 2010;
int n, m;
int h[N], e[M], ne[M], idx;
bool st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void bfs()
{
queue<int> q;
q.push(1);
st[1] = true;
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while (m--)
{
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
bfs();
for (int i = 1; i <= n; i++) // 遍历结点1~n
{
if (!st[i])
{
cout << -1 << endl;
return 0;
}
}
cout << 1 << endl;
}