Graph DFS Topological Sort (Go)

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

GoData Integrity

Code

gosnippet
21 lines
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
}

How it works

Count the function topologicalSort as the entire surface area of Graph DFS Topological Sort (Go).

for _, neighbor := range graph[node] { if err := dfs(neighbor); err != nil { return err } } is the loop that carries the per-item work. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.

Points of care

  • error is part of the return tuple, so every caller decides what failure means.

Applying it

Entry signature: func topologicalSort(graph map[string][]string) ([]string, error)

Statements that matter

for n := range graph { if color[n] == 0 { if err := dfs(n); err != nil { return nil, err } } }
for _, neighbor := range graph[node] { if err := dfs(neighbor); err != nil { return err } }
if color[node] == 1 { return errors.New("cycle at " + node) }

Interactive Tools for This Topic

FAQ

What happens when a call fails?
As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `topologicalSort` at load time.