Skip to content

Commit

Permalink
feat: add FindSource function
Browse files Browse the repository at this point in the history
Signed-off-by: Akash Kumar <meakash7902@gmail.com>
  • Loading branch information
AkashKumar7902 committed Mar 6, 2024
1 parent a999520 commit 7c06cfa
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions dag.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,26 @@ func TransitiveReduction[K comparable, T any](g Graph[K, T]) (Graph[K, T], error

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

0 comments on commit 7c06cfa

Please sign in to comment.