toposort.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package toposort
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. )
  7. // Reworked from https://github.com/philopon/go-toposort
  8. type Graph struct {
  9. // Outgoing connections for every node.
  10. outputs map[string]map[string]int
  11. // How many parents each node has.
  12. inputs map[string]int
  13. }
  14. // NewGraph initializes a new Graph.
  15. func NewGraph() *Graph {
  16. return &Graph{
  17. inputs: map[string]int{},
  18. outputs: map[string]map[string]int{},
  19. }
  20. }
  21. // Copy clones the graph and returns the independent copy.
  22. func (g *Graph) Copy() *Graph {
  23. clone := NewGraph()
  24. for k, v := range g.inputs {
  25. clone.inputs[k] = v
  26. }
  27. for k1, v1 := range g.outputs {
  28. m := map[string]int{}
  29. clone.outputs[k1] = m
  30. for k2, v2 := range v1 {
  31. m[k2] = v2
  32. }
  33. }
  34. return clone
  35. }
  36. // AddNode inserts a new node into the graph.
  37. func (g *Graph) AddNode(name string) bool {
  38. if _, exists := g.outputs[name]; exists {
  39. return false
  40. }
  41. g.outputs[name] = make(map[string]int)
  42. g.inputs[name] = 0
  43. return true
  44. }
  45. // AddNodes inserts multiple nodes into the graph at once.
  46. func (g *Graph) AddNodes(names ...string) bool {
  47. for _, name := range names {
  48. if ok := g.AddNode(name); !ok {
  49. return false
  50. }
  51. }
  52. return true
  53. }
  54. // AddEdge inserts the link from "from" node to "to" node.
  55. func (g *Graph) AddEdge(from, to string) int {
  56. m, ok := g.outputs[from]
  57. if !ok {
  58. return 0
  59. }
  60. m[to] = len(m) + 1
  61. ni := g.inputs[to] + 1
  62. g.inputs[to] = ni
  63. return ni
  64. }
  65. // ReindexNode updates the internal representation of the node after edge removals.
  66. func (g *Graph) ReindexNode(node string) {
  67. children, ok := g.outputs[node]
  68. if !ok {
  69. return
  70. }
  71. i := 1
  72. for key := range children {
  73. children[key] = i
  74. i++
  75. }
  76. }
  77. func (g *Graph) unsafeRemoveEdge(from, to string) {
  78. delete(g.outputs[from], to)
  79. g.inputs[to]--
  80. }
  81. // RemoveEdge deletes the link from "from" node to "to" node.
  82. // Call ReindexNode(from) after you finish modifying the edges.
  83. func (g *Graph) RemoveEdge(from, to string) bool {
  84. if _, ok := g.outputs[from]; !ok {
  85. return false
  86. }
  87. g.unsafeRemoveEdge(from, to)
  88. return true
  89. }
  90. // Toposort sorts the nodes in the graph in topological order.
  91. func (g *Graph) Toposort() ([]string, bool) {
  92. L := make([]string, 0, len(g.outputs))
  93. S := make([]string, 0, len(g.outputs))
  94. for n := range g.outputs {
  95. if g.inputs[n] == 0 {
  96. S = append(S, n)
  97. }
  98. }
  99. sort.Strings(S)
  100. for len(S) > 0 {
  101. var n string
  102. n, S = S[0], S[1:]
  103. L = append(L, n)
  104. ms := make([]string, len(g.outputs[n]))
  105. for m, i := range g.outputs[n] {
  106. ms[i-1] = m
  107. }
  108. for _, m := range ms {
  109. g.unsafeRemoveEdge(n, m)
  110. if g.inputs[m] == 0 {
  111. S = append(S, m)
  112. }
  113. }
  114. }
  115. N := 0
  116. for _, v := range g.inputs {
  117. N += v
  118. }
  119. if N > 0 {
  120. return L, false
  121. }
  122. return L, true
  123. }
  124. // BreadthSort sorts the nodes in the graph in BFS order.
  125. func (g *Graph) BreadthSort() []string {
  126. L := make([]string, 0, len(g.outputs))
  127. S := make([]string, 0, len(g.outputs))
  128. for n := range g.outputs {
  129. if g.inputs[n] == 0 {
  130. S = append(S, n)
  131. }
  132. }
  133. visited := map[string]bool{}
  134. for len(S) > 0 {
  135. node := S[0]
  136. S = S[1:]
  137. if _, exists := visited[node]; !exists {
  138. L = append(L, node)
  139. visited[node] = true
  140. for child := range g.outputs[node] {
  141. S = append(S, child)
  142. }
  143. }
  144. }
  145. return L
  146. }
  147. // FindCycle returns the cycle in the graph which contains "seed" node.
  148. func (g *Graph) FindCycle(seed string) []string {
  149. type edge struct {
  150. node string
  151. parent string
  152. }
  153. S := make([]edge, 0, len(g.outputs))
  154. S = append(S, edge{seed, ""})
  155. visited := map[string]string{}
  156. for len(S) > 0 {
  157. e := S[0]
  158. S = S[1:]
  159. if parent, exists := visited[e.node]; !exists || parent == "" {
  160. visited[e.node] = e.parent
  161. for child := range g.outputs[e.node] {
  162. S = append(S, edge{child, e.node})
  163. }
  164. }
  165. if e.node == seed && e.parent != "" {
  166. result := []string{}
  167. node := e.parent
  168. for node != seed {
  169. result = append(result, node)
  170. node = visited[node]
  171. }
  172. result = append(result, seed)
  173. // reverse
  174. for left, right := 0, len(result)-1; left < right; left, right = left+1, right-1 {
  175. result[left], result[right] = result[right], result[left]
  176. }
  177. return result
  178. }
  179. }
  180. return []string{}
  181. }
  182. // FindParents returns the other ends of incoming edges.
  183. func (g *Graph) FindParents(to string) []string {
  184. result := []string{}
  185. for node, children := range g.outputs {
  186. if _, exists := children[to]; exists {
  187. result = append(result, node)
  188. }
  189. }
  190. return result
  191. }
  192. // FindChildren returns the other ends of outgoing edges.
  193. func (g *Graph) FindChildren(from string) []string {
  194. result := []string{}
  195. for child := range g.outputs[from] {
  196. result = append(result, child)
  197. }
  198. return result
  199. }
  200. // Serialize outputs the graph in Graphviz format.
  201. func (g *Graph) Serialize(sorted []string) string {
  202. node2index := map[string]int{}
  203. for index, node := range sorted {
  204. node2index[node] = index
  205. }
  206. var buffer bytes.Buffer
  207. buffer.WriteString("digraph Hercules {\n")
  208. nodesFrom := []string{}
  209. for nodeFrom := range g.outputs {
  210. nodesFrom = append(nodesFrom, nodeFrom)
  211. }
  212. sort.Strings(nodesFrom)
  213. for _, nodeFrom := range nodesFrom {
  214. links := []string{}
  215. for nodeTo := range g.outputs[nodeFrom] {
  216. links = append(links, nodeTo)
  217. }
  218. sort.Strings(links)
  219. for _, nodeTo := range links {
  220. buffer.WriteString(fmt.Sprintf(" \"%d %s\" -> \"%d %s\"\n",
  221. node2index[nodeFrom], nodeFrom, node2index[nodeTo], nodeTo))
  222. }
  223. }
  224. buffer.WriteString("}")
  225. return buffer.String()
  226. }