@@ -0,0 +1,90 @@
|
||||
package graphs
|
||||
|
||||
type Number interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 |
|
||||
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
|
||||
~float32 | ~float64
|
||||
}
|
||||
|
||||
// Weighted Graph , undirected
|
||||
type WeightedGraph[T comparable, W Number] struct {
|
||||
adjList map[T]map[T]W
|
||||
}
|
||||
|
||||
// NewWeightedGraph() -> Creates a Weighted Graph.
|
||||
//
|
||||
// gg := graphs.NewWeightedGraph[string, int]()
|
||||
func NewWeightedGraph[T comparable, W Number]() *WeightedGraph[T, W] {
|
||||
gp := &WeightedGraph[T, W]{
|
||||
adjList: make(map[T]map[T]W),
|
||||
}
|
||||
|
||||
return gp
|
||||
}
|
||||
|
||||
// AddVertex() -> add vertex connected to vertex with weight
|
||||
func (gp *WeightedGraph[T, W]) AddVertex(newVertex T, connectToVertex T, weight W) bool {
|
||||
// early return
|
||||
if newVertex == connectToVertex {
|
||||
return false
|
||||
}
|
||||
|
||||
gp.AddIsolatedVertex(newVertex)
|
||||
gp.AddIsolatedVertex(connectToVertex)
|
||||
|
||||
_, exist := gp.adjList[newVertex][connectToVertex]
|
||||
|
||||
if !exist {
|
||||
gp.adjList[newVertex][connectToVertex] = weight
|
||||
gp.adjList[connectToVertex][newVertex] = weight
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// AddIsolatedVertex() -> Creates an isolated Vertex returns True if ok ,
|
||||
// false if vertex already exist
|
||||
func (gp *WeightedGraph[T, W]) AddIsolatedVertex(newVertex T) bool {
|
||||
_, exist := gp.adjList[newVertex]
|
||||
if !exist {
|
||||
gp.adjList[newVertex] = make(map[T]W)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ConnectEdge() -> Connects two already existing vertices with a weighted edge.
|
||||
// Returns false if either vertex is missing or the edge is already there.
|
||||
func (gp *WeightedGraph[T, W]) ConnectEdge(vertex T, to T, weight W) bool {
|
||||
if _, exist := gp.adjList[vertex]; !exist {
|
||||
return false
|
||||
}
|
||||
|
||||
if _, exist := gp.adjList[to]; !exist {
|
||||
return false
|
||||
}
|
||||
|
||||
return gp.AddVertex(vertex, to, weight)
|
||||
}
|
||||
|
||||
// Display()
|
||||
func (gp *WeightedGraph[T, W]) Display() map[T]map[T]W {
|
||||
return gp.adjList
|
||||
}
|
||||
|
||||
// Order() -> returns the amount of Vertices
|
||||
func (gp *WeightedGraph[T, W]) Order() int {
|
||||
return len(gp.adjList)
|
||||
}
|
||||
|
||||
// Size() -> returns the amount of Edges
|
||||
func (gp *WeightedGraph[T, W]) Size() int {
|
||||
var size int
|
||||
|
||||
for _, inner := range gp.adjList {
|
||||
size += len(inner)
|
||||
}
|
||||
|
||||
return size / 2
|
||||
}
|
||||
Reference in New Issue
Block a user