Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP]: add FindSource function #169

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions dag.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,26 @@

return transitiveReduction, nil
}

// FindSources returns all source vertices in a directed acyclic graph. A source
// vertex is a vertex with no incoming edges.
//
// FindSources only works for directed acyclic graph.
func FindSources[K comparable, T any](g Graph[K, T]) ([]K, error) {
if !g.Traits().IsDirected {
return nil, fmt.Errorf("cannot find source in a non-directed acyclic graph")
}

predecessorMap, err := g.PredecessorMap()
if err != nil {
return nil, fmt.Errorf("failed to get predecessor map: %w", err)
}

var sources []K
for vertex, predecessors := range predecessorMap {
if len(predecessors) == 0 {
sources = append(sources, vertex)
}
}
return sources, nil
}

Check failure on line 242 in dag.go

View workflow job for this annotation

GitHub Actions / Unit Tests (1.20.x)

syntax error: unexpected var after top level declaration
Loading