Skip to content

Commit

Permalink
Merge pull request #48 from hmdsefi/dev
Browse files Browse the repository at this point in the history
update tarjan comments
  • Loading branch information
hmdsefi committed Mar 11, 2023
2 parents 6212b24 + f9e1c14 commit a5366ed
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions connectivity/tarjan.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@ package connectivity

import "github.com/hmdsefi/gograph"

// Tarjan's algorithm is based on depth-first search and is widely used for
// finding strongly connected components in a graph. The algorithm is efficient
// and has a time complexity of O(V+E), where V is the number of vertices and E
// is the number of edges in the graph.

// tarjanVertex wraps the gograph.Vertex struct to add new fields to it.
type tarjanVertex[T comparable] struct {
*gograph.Vertex[T]
index int
lowLink int
onStack bool
*gograph.Vertex[T] // the vertex that being wrapped.
index int // represents the order in which a vertex is visited during the DFS search.
lowLink int // the minimum index of any vertex reachable from the vertex during the search.
onStack bool // a boolean flag that shows if the vertex is in the stack or not.
}

func newTarjanVertex[T comparable](vertex *gograph.Vertex[T]) *tarjanVertex[T] {
Expand All @@ -24,6 +30,10 @@ func newTarjanSCCS[T comparable](vertices map[T]*tarjanVertex[T]) *tarjanSCCS[T]
return &tarjanSCCS[T]{vertices: vertices}
}

// tarjan is the entry point to the algorithm. It initializes the index,
// stack, and sccs variables and then loops through all the vertices in
// the graph. It returns a slice of vertices' slice, where each inner
// slice represents a strongly connected component of the graph.
func tarjan[T comparable](g gograph.Graph[T]) [][]*gograph.Vertex[T] {
var (
index int
Expand Down Expand Up @@ -57,6 +67,11 @@ func tarjan[T comparable](g gograph.Graph[T]) [][]*gograph.Vertex[T] {
return result
}

// visit updates the index and lowLink values of the vertex, adds it to
// the stack, and recursively calls itself on each of its neighbors. If
// a neighbor has not been visited before, its index and lowLink values
// are updated, and the recursion continues. If a neighbor has already
// been visited and is still on the stack, its lowLink value is updated.
func (t *tarjanSCCS[T]) visit(
v *tarjanVertex[T],
index *int,
Expand Down Expand Up @@ -95,6 +110,7 @@ func (t *tarjanSCCS[T]) visit(
}
}

// min is a helper function that returns the minimum of two integers.
func min(x, y int) int {
if x < y {
return x
Expand Down

0 comments on commit a5366ed

Please sign in to comment.