Repository navigation
Expand file tree
/
Copy pathgraphmatrix.go
More file actions
94 lines (75 loc) · 1.82 KB
/
Copy pathgraphmatrix.go
File metadata and controls
94 lines (75 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package graph
import "slices"
type NewGraphMatrixParams[T comparable] struct {
Directed bool
Weighted bool
VertexList []T
}
type GraphMatrix[T comparable] struct {
directed bool
weighted bool
vertexList []T
matrix [][]int
}
func Constructor[T comparable] (params NewGraphMatrixParams[T]) *GraphMatrix[T] {
vertexList := params.VertexList
directed := params.Directed
weighted := params.Weighted
matrix := make([][] int, len(vertexList))
for i := range matrix {
matrix[i] = make([]int, len(vertexList))
}
return &GraphMatrix[T]{
directed: directed,
weighted: weighted,
vertexList: vertexList,
matrix: matrix,
}
}
func (g *GraphMatrix[T]) AddEdge(from, to int, weight int) {
edgeWeight := weight
if(!g.weighted) {
edgeWeight = 1
}
g.matrix[from][to] = edgeWeight
if !g.directed {
g.matrix[to][from] = edgeWeight
}
}
func (g *GraphMatrix[T]) RemoveEdge(from, to int) {
g.matrix[from][to] = 0
if !g.directed {
g.matrix[to][from] = 0
}
}
func (g *GraphMatrix[T]) AddVertex(vertex T) {
newRow := make([]int, len(g.vertexList))
g.matrix = append(g.matrix, newRow)
for i:= range g.matrix {
g.matrix[i] = append(g.matrix[i], 0)
}
g.vertexList = append(g.vertexList, vertex)
}
func (g *GraphMatrix[T]) RemoveVertex(vertex T) {
index := slices.Index(g.vertexList, vertex)
if(index == -1) {
return
}
g.matrix = append(g.matrix[:index], g.matrix[index+1:]...)
for i := range g.matrix {
g.matrix[i] = append(g.matrix[i][:index], g.matrix[i][index+1:]...)
}
g.vertexList = append(g.vertexList[:index], g.vertexList[index+1:]...)
}
func (g *GraphMatrix[T]) GetMatrix() [][]int {
return g.matrix
}
func (g *GraphMatrix[T]) GetVertexList() []T {
return g.vertexList
}
func (g *GraphMatrix[T]) IsDirected() bool {
return g.directed
}
func (g *GraphMatrix[T]) IsWeighted() bool {
return g.weighted
}