Skip to content

Instantly share code, notes, and snippets.

@wahyurudiyan
Created January 4, 2024 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wahyurudiyan/1ae012d17dd53097c1b932da9734e468 to your computer and use it in GitHub Desktop.
Save wahyurudiyan/1ae012d17dd53097c1b932da9734e468 to your computer and use it in GitHub Desktop.
Simple graph data structure without distance value of each nodes.
package main
import (
"fmt"
)
type Graph struct {
Vertice []*Vertex
}
type Vertex struct {
Key int
Adjacent []*Vertex
}
func (g *Graph) AddVertex(vertex int) error {
// Check is vertex available
if isExist(vertex, g.Vertice) {
return fmt.Errorf("vertex is exist")
}
// Insert vertex into graph
g.Vertice = append(g.Vertice, &Vertex{
Key: vertex,
})
return nil
}
func (g *Graph) GetVertex(vertex int) *Vertex {
for i, v := range g.Vertice {
if v.Key == vertex {
return g.Vertice[i]
}
}
return nil
}
func (g *Graph) AddEdge(from int, dest int) error {
// Check is vertext exists
fromVertex := g.GetVertex(from)
destVertex := g.GetVertex(dest)
if fromVertex == nil || destVertex == nil {
return fmt.Errorf("vertex from (%v) --> (%v) is not valid", from, dest)
}
// Check is adjacent vertex exists or not
if isExist(destVertex.Key, fromVertex.Adjacent) {
return fmt.Errorf("edge from vertex (%v) --> (%v) already exists", fromVertex.Key, destVertex.Key)
}
// insert new adjacent for from and dest vertex
fromVertex.Adjacent = append(fromVertex.Adjacent, destVertex)
return nil
}
func (g *Graph) Print() {
for _, val := range g.Vertice {
fmt.Printf("(%v): ", val.Key)
for i, adj := range val.Adjacent {
if i > 0 {
fmt.Printf(" -> ")
}
fmt.Printf("(%v)", adj.Key)
}
fmt.Println()
}
}
func isExist(key int, vertices []*Vertex) bool {
for _, v := range vertices {
if v.Key == key {
return true
}
}
return false
}
func main() {
graph := &Graph{}
graph.AddVertex(0)
graph.AddVertex(1)
graph.AddVertex(2)
graph.AddVertex(3)
graph.AddVertex(4)
graph.AddVertex(5)
graph.AddEdge(0, 1)
graph.AddEdge(0, 2)
graph.AddEdge(0, 5)
graph.AddEdge(1, 0)
graph.AddEdge(2, 0)
graph.AddEdge(5, 0)
graph.AddEdge(2, 1)
graph.AddEdge(2, 3)
graph.AddEdge(2, 6)
graph.AddEdge(1, 2)
graph.AddEdge(3, 2)
graph.AddEdge(6, 2)
graph.AddEdge(6, 5)
graph.AddEdge(5, 6)
graph.Print()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment