class Solution {
public:
int minimumSemesters(int n, vector<vector<int>>& relations) {
vector<vector<int>> edges(n + 1);
vector<int> inDegree(n + 1, 0);
for (const auto& info : relations) {
edges[info[0]].push_back(info[1]);
inDegree[info[1]]++;
}
queue<int> que;
for (int i = 1; i <= n; i++) {
if (inDegree[i] == 0)
que.push(i);
}
vector<int> cost(n + 1, 0);
int res = 0, count = n;
while (!que.empty()) {
int current = que.front();
que.pop();
count--;
cost[current]++;
res = max(res, cost[current]);
for (int v : edges[current]) {
cost[v] = max(cost[v], cost[current]);
if (--inDegree[v] == 0)
que.push(v);
}
}
return count == 0 ? res : -1;
}
};