Skip to content

Commit f0f4727

Browse files
authored
Merge pull request #73 from hmdsefi/dev
fix finding cycle in directed graph
2 parents b4feb78 + c50a6da commit f0f4727

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

base.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ func (g *baseGraph[T]) AddEdge(from, to *Vertex[T], options ...EdgeOptionFunc) (
6969
return nil, ErrEdgeAlreadyExists
7070
}
7171

72+
from = g.vertices[from.label]
73+
to = g.vertices[to.label]
74+
7275
from.neighbors = append(from.neighbors, to)
7376
to.inDegree++
7477

base_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package gograph
22

33
import (
4+
"errors"
45
"reflect"
56
"testing"
67
)
@@ -890,3 +891,24 @@ func Test_baseGraph_ContainsVertex(t *testing.T) {
890891
t.Errorf("expected len to be %d, but receive %d", 3, len(edges))
891892
}
892893
}
894+
895+
func Test_baseGraph_Cyclic(t *testing.T) {
896+
graph := New[int](Acyclic())
897+
898+
_, err := graph.AddEdge(NewVertex(1), NewVertex(2))
899+
if err != nil {
900+
t.Fatal(err)
901+
}
902+
_, err = graph.AddEdge(NewVertex(2), NewVertex(3))
903+
if err != nil {
904+
t.Fatal(err)
905+
}
906+
_, err = graph.AddEdge(NewVertex(3), NewVertex(1))
907+
if err == nil {
908+
t.Fatalf("expected error, but got nil")
909+
}
910+
911+
if !errors.Is(err, ErrDAGCycle) {
912+
t.Errorf("expected error %s, but got %s", ErrDAGCycle, err)
913+
}
914+
}

0 commit comments

Comments
 (0)