三叶题解
时间复杂度: O ( n + m ) O(n+m) O(n+m)
空间复杂度: O ( n + m ) O(n+m) O(n+m)
class Solution{
int N = 100010, M = 5010, idx;
int[] in = new int[N];// in[i] 表示节点 i 的入度
int[] h = new int[N];
int[] e = new int[N];
int[] ne = new int[N];
// 添加一条边 a --> b
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
in[b]++;
}
public boolean canFinish(int n, int[][] g)
{
Arrays.fill(h, -1);//初始化头结点
for (int[] a : g)
add(a[1], a[0]);
int ans = 0;
Queue q = new LinkedList<>();
for (int i = 0; i < n; i++)
if (in[i] == 0)
q.add(i);
while (!q.isEmpty())
{
int x = q.poll();
ans++;
for (int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
in[j]--;
if (in[j] == 0)
q.add(j);
}
}
return ans == n;
}
}