思路一:深度优先搜索
1.首先我们将这些边集转化为图,题目的意思可以转化为,要访问一个节点,必须访问完其指向的其他节点才能够访问。
2.这样,我们可以采取深度优先搜索的思想,假设现在访问节点cur,循环遍历访问它指向的其他未访问过的节点(
n
e
x
t
i
,
n
e
x
t
i
+
1
,
n
e
x
t
i
+
2
next_i ,next_{i+1} , next_{i+2}
nexti,nexti+1,nexti+2),也就是依次进行
d
f
s
(
n
e
x
t
i
)
,
d
f
s
(
n
e
x
t
i
+
1
)
.
.
.
.
.
.
dfs(next_i),dfs(next_{i+1})......
dfs(nexti),dfs(nexti+1)......,如何确定这些未访问过的节点呢?我们可以采取常规的vistited[n]数组进行记录节点的访问情况,0代表未访问,1代表正在访问,2代表访问过,依次类推,直到访问完cur指向的所有节点才能够访问cur。
3.但我们还需要考虑一种特殊情况,也就是存在环的情况,如果存在环会发生什么情况?假设当前访问节点cur,我们循环遍历其指向的其他节点(
n
e
x
t
i
,
n
e
x
t
i
+
1
,
n
e
x
t
i
+
2
next_i ,next_{i+1} , next_{i+2}
nexti,nexti+1,nexti+2),如果
v
i
s
t
i
t
e
d
[
n
e
x
t
k
]
=
=
1
vistited[ next_k ]==1
vistited[nextk]==1,也就是k是当前访问节点的祖先之一,证明存在一条边回指向了cur的祖先节点,也就是存在环。
代码:
class Solution {
public:
vector<vector<int>> graph;
vector<int> res;
bool dfs(int c,vector<int> &isVistied)
{
isVistied[c]=1;//c正在搜索
for(int i=0;i<graph[c].size();i++)
{
if(isVistied[graph[c][i]]==1)
{
return false;
}
else if(isVistied[graph[c][i]]==0)
{
if(!dfs(graph[c][i],isVistied))
return false;
}
//如果后继节点next已经出现在当前dfs正在搜索路径的之上,next状态为1,证明存在环
//如果后继节点next在其后代结点搜索过程中因为存在环退出搜索,也需要向上返回false
}
isVistied[c]=2;//搜索完成
res.push_back(c);
return true;
}
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> isVistied(numCourses,0);
graph.assign(numCourses,vector<int>());
for(auto r: prerequisites)
{
graph[r[0]].push_back(r[1]);
}
for(int i=0;i<numCourses;i++)
{
if(isVistied[i]==0)
{
if(!dfs(i,isVistied))
return {};
}
}
return res;
}
};
思路二:广度优先搜索
1.维护一个数组in记录每个节点的入度
2.维护一个入度为0的集合s
3.每次从集合当中取出一个节点,将其插入结果数组res末尾,依据邻接矩阵,将其指向的所有节点的入度减一,如果在减一过程中发现某个节点入度为0则将其加入s
4.一直到s为空
5.如果res的大小等于节点个数证明存在环。
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
queue<int> q;
vector<int> res;
vector<int> inDegree(numCourses,0);
vector<vector<int>> graph(numCourses,vector<int>());
for(auto r: prerequisites)
{
graph[r[1]].push_back(r[0]);
inDegree[r[0]]++;
}
for(int i=0;i<numCourses;i++)
{
if(inDegree[i]==0)
{
q.push(i);
}
}
while(!q.empty())
{
int t=q.front();
q.pop();
res.push_back(t);
for(int i=0;i<graph[t].size();i++)
{
inDegree[graph[t][i]]--;
if(inDegree[graph[t][i]]==0)
{
q.push(graph[t][i]);
}
}
}
if(res.size()!=numCourses)
res={};
return res;
}
};