-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkahn-topological-sort.R
52 lines (41 loc) · 1.16 KB
/
kahn-topological-sort.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#
# Sami Hossain
# 04-22-2021
# Kahn's Topological Sorting Algorithm
# Recursive graph reductions based on nodes of indegree 0
if (!requireNamespace("BiocManager", quietly = TRUE)){ #for pcalg library
install.packages("BiocManager")
library('BiocManager')
BiocManager::install("RBGL")
}
############
### SETUP ##
############
library(pcalg)
library(igraph)
nodes <- 10
graph <- randomDAG(nodes, prob= 0.3, lB = 1, uB = 1) %>% #generating a random Directed Acyclic Graph
graph_from_graphnel()
plot(graph)
################
### ALGORITHM ##
################
#by definition of DAG, there is at least one vertex with indegree[incoming edges] equal to 0
topo_ordering <<- c()
getNextVertex <- function(){
for(i in nodes:1){
if(sum(graph[,i]) == 0 && !(i %in% topo_ordering)){
return (i)
}
}
return (NULL)
}
repeat{
v <- getNextVertex()
if(is.null(v)){break} #no indegree edges left -> ordering is complete
#rip out the vertex and its edges from the graph and add it to the topo ordering
graph[v,] <- FALSE
topo_ordering <- c(topo_ordering, v)
graph[]
}
print(topo_ordering)