Created
September 12, 2023 08:38
-
-
Save gabrielbussolo/d1292e8e56e470561e9e37798ad964f7 to your computer and use it in GitHub Desktop.
Simple graph implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Graph struct { | |
vertices map[int][]int | |
} | |
func (g *Graph) AddVertice(vert int) { | |
if g.vertices == nil { | |
g.vertices = make(map[int][]int) | |
} | |
if _, ok := g.vertices[vert]; !ok { | |
g.vertices[vert] = []int{} | |
} | |
} | |
func (g *Graph) AddEdge(node1, node2 int) { | |
if _, ok := g.vertices[node1]; !ok { | |
return | |
} | |
if _, ok := g.vertices[node2]; !ok { | |
return | |
} | |
g.vertices[node1] = append(g.vertices[node1], node2) | |
g.vertices[node2] = append(g.vertices[node2], node1) | |
} | |
func (g *Graph) Print() { | |
for vertex, neighbors := range g.vertices { | |
fmt.Printf("%d -> ", vertex) | |
for _, neighbor := range neighbors { | |
fmt.Printf("%d ", neighbor) | |
} | |
fmt.Println() | |
} | |
} | |
func main() { | |
g := Graph{} | |
g.AddVertice(0) | |
g.AddVertice(1) | |
g.AddVertice(2) | |
g.AddVertice(3) | |
g.AddVertice(4) | |
g.AddVertice(5) | |
g.AddVertice(6) | |
g.AddEdge(3, 1) | |
g.AddEdge(3, 4) | |
g.AddEdge(4, 2) | |
g.AddEdge(4, 5) | |
g.AddEdge(1, 2) | |
g.AddEdge(1, 0) | |
g.AddEdge(0, 2) | |
g.AddEdge(6, 5) | |
g.Print() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment