Graph DFS Topological Sort (Go)

Perform topological sort on a Go DAG using DFS with cycle detection via tri-color marking.

GoData Integrity

Code

snippet
package main

import "errors"

func topologicalSort(graph map[string][]string) ([]string, error) {
	color := map[string]int{}
	var result []string
	var dfs func(node string) error
	dfs = func(node string) error {
		if color[node] == 1 { return errors.New("cycle at " + node) }
		if color[node] == 2 { return nil }
		color[node] = 1
		for _, neighbor := range graph[node] { if err := dfs(neighbor); err != nil { return err } }
		color[node] = 2
		result = append(result, node)
		return nil
	}
	for n := range graph { if color[n] == 0 { if err := dfs(n); err != nil { return nil, err } } }
	for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { result[i], result[j] = result[j], result[i] }
	return result, nil
}