解释vector<int> eventualSafeNodes(vector<vector<int>> &graph)
时间: 2023-10-22 13:32:08 浏览: 32
eventualSafeNodes函数的作用是找出一个有向图中所有最终安全的节点。
函数的输入是一个二维向量,表示有向图中每个节点的出边列表。例如,如果输入为[[1,2],[2,3],[5],[0],[5],[],[]],表示节点0有一条指向节点1和节点2的出边,节点1有一条指向节点2的出边,节点2有一条指向节点3的出边,节点3、4、5、6没有出边。
函数的输出是一个整数向量,表示所有最终安全的节点编号。最终安全的节点是指在该节点出发的路径上不存在环。例如,在上述输入中,节点0、1、3、4、6都是最终安全的节点,因为从这些节点出发的路径上不存在环。
函数的实现可以使用深度优先搜索算法,每次从一个节点开始,遍历所有出边指向的节点,并判断是否存在环。如果存在环,则该节点不是最终安全的节点,否则继续遍历下一个节点。为了避免重复遍历已经判断过的节点,可以使用一个状态数组来记录每个节点的状态,状态分为未访问、正在访问和已完成三种。对于已完成的节点,可以直接跳过。对于正在访问的节点,如果在遍历过程中遇到了该节点,则表示存在环,该节点不是最终安全的节点。对于未访问的节点,需要先将其状态设置为正在访问,然后再递归遍历该节点的出边指向的节点。如果所有出边指向的节点都是最终安全的节点,则该节点也是最终安全的节点。
相关问题
vector<int> eventualSafeNodes(vector<vector<int>> &graph)
graph) {
int n = graph.size();
vector<int> indegrees(n, 0); // indegrees[i] stores the indegree of node i
vector<vector<int>> adjList(n, vector<int>()); // adjList[i] stores the nodes that have an edge from i
queue<int> q; // queue for BFS
// Build adjacency list and indegrees
for (int i = 0; i < n; i++) {
for (int j : graph[i]) {
adjList[i].push_back(j);
indegrees[j]++;
}
}
// Add nodes with indegree 0 to the queue
for (int i = 0; i < n; i++) {
if (indegrees[i] == 0) {
q.push(i);
}
}
// BFS
while (!q.empty()) {
int curr = q.front();
q.pop();
for (int next : adjList[curr]) {
indegrees[next]--;
if (indegrees[next] == 0) {
q.push(next);
}
}
}
// Add nodes with indegree 0 to the result
vector<int> res;
for (int i = 0; i < n; i++) {
if (indegrees[i] == 0) {
res.push_back(i);
}
}
return res;
}
typedef pair<int,int>pii;vector<pii>graph[N];改写成普通的方式
这段代码可以改写成以下的普通方式:
```
#include <vector>
#include <utility> // for std::pair
const int N = 100; // 假设 N = 100
typedef std::pair<int, int> pii;
std::vector<pii> graph[N];
```
其中,`std::pair`是C++标准库中的一个模板类,用来表示一对值,这里用来表示两个整数。`std::vector`是C++标准库中的一个模板类,表示动态数组。这里使用了模板参数`<pii>`,表示这个vector中存储的是`std::pair<int, int>`类型的数据。