Skip to content

Commit

Permalink
Merge pull request #73 from hmdsefi/dev
Browse files Browse the repository at this point in the history
fix finding cycle in directed graph
  • Loading branch information
hmdsefi authored Jul 22, 2024
2 parents b4feb78 + c50a6da commit f0f4727
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions base.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ func (g *baseGraph[T]) AddEdge(from, to *Vertex[T], options ...EdgeOptionFunc) (
return nil, ErrEdgeAlreadyExists
}

from = g.vertices[from.label]
to = g.vertices[to.label]

from.neighbors = append(from.neighbors, to)
to.inDegree++

Expand Down
22 changes: 22 additions & 0 deletions base_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gograph

import (
"errors"
"reflect"
"testing"
)
Expand Down Expand Up @@ -890,3 +891,24 @@ func Test_baseGraph_ContainsVertex(t *testing.T) {
t.Errorf("expected len to be %d, but receive %d", 3, len(edges))
}
}

func Test_baseGraph_Cyclic(t *testing.T) {
graph := New[int](Acyclic())

_, err := graph.AddEdge(NewVertex(1), NewVertex(2))
if err != nil {
t.Fatal(err)
}
_, err = graph.AddEdge(NewVertex(2), NewVertex(3))
if err != nil {
t.Fatal(err)
}
_, err = graph.AddEdge(NewVertex(3), NewVertex(1))
if err == nil {
t.Fatalf("expected error, but got nil")
}

if !errors.Is(err, ErrDAGCycle) {
t.Errorf("expected error %s, but got %s", ErrDAGCycle, err)
}
}

0 comments on commit f0f4727

Please sign in to comment.