forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
57 lines (48 loc) · 1.48 KB
/
graph.go
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
// This file contains the simple structural implementation of undirected
// graph, used in coloring algorithms.
// Author(s): [Shivam](https://github.com/Shivam010)
package coloring
import "errors"
// Color provides a type for vertex color
type Color int
// Graph provides a structure to store an undirected graph.
// It is safe to use its empty object.
type Graph struct {
vertices int
edges map[int]map[int]struct{}
}
// AddVertex will add a new vertex in the graph, if the vertex already
// exist it will do nothing
func (g *Graph) AddVertex(v int) {
if g.edges == nil {
g.edges = make(map[int]map[int]struct{})
}
// Check if vertex is present or not
if _, ok := g.edges[v]; !ok {
g.vertices++
g.edges[v] = make(map[int]struct{})
}
}
// AddEdge will add a new edge between the provided vertices in the graph
func (g *Graph) AddEdge(one, two int) {
// Add vertices: one and two to the graph if they are not present
g.AddVertex(one)
g.AddVertex(two)
// and finally add the edges: one->two and two->one for undirected graph
g.edges[one][two] = struct{}{}
g.edges[two][one] = struct{}{}
}
func (g *Graph) ValidateColorsOfVertex(colors map[int]Color) error {
if g.vertices != len(colors) {
return errors.New("coloring: not all vertices of graph are colored")
}
// check colors
for vertex, neighbours := range g.edges {
for nb := range neighbours {
if colors[vertex] == colors[nb] {
return errors.New("coloring: same colors of neighbouring vertex")
}
}
}
return nil
}