Created
February 24, 2019 13:47
-
-
Save itchyny/b6250933afaf3fae853a623e349d2a3e to your computer and use it in GitHub Desktop.
Golang tsort implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"os" | |
) | |
type edge struct{ from, to int } | |
func main() { | |
var edges = []edge{ | |
{3, 8}, | |
{3, 10}, | |
{5, 11}, | |
{7, 8}, | |
{7, 11}, | |
{8, 9}, | |
{11, 2}, | |
{11, 9}, | |
{11, 10}, | |
} | |
l, err := tsort(edges) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "%s\n", err) | |
} else { | |
fmt.Printf("%+v\n", l) | |
} | |
} | |
func tsort(edges []edge) ([]int, error) { | |
inEdges := make(map[int]map[int]struct{}) | |
outEdges := make(map[int]map[int]struct{}) | |
for _, e := range edges { | |
if _, ok := inEdges[e.to]; !ok { | |
inEdges[e.to] = make(map[int]struct{}) | |
} | |
inEdges[e.to][e.from] = struct{}{} | |
if _, ok := outEdges[e.from]; !ok { | |
outEdges[e.from] = make(map[int]struct{}) | |
} | |
outEdges[e.from][e.to] = struct{}{} | |
} | |
s := make(map[int]struct{}) | |
for m := range outEdges { | |
if len(inEdges[m]) == 0 { | |
s[m] = struct{}{} | |
} | |
} | |
var l []int | |
for len(s) > 0 { | |
var n int | |
for n = range s { | |
break | |
} | |
delete(s, n) | |
l = append(l, n) | |
for m := range outEdges[n] { | |
delete(outEdges[n], m) | |
delete(inEdges[m], n) | |
if len(inEdges[m]) == 0 { | |
s[m] = struct{}{} | |
} | |
} | |
} | |
for _, es := range inEdges { | |
if len(es) > 0 { | |
return nil, errors.New("has cycle") | |
} | |
} | |
return l, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With cycle detection error.