package main
import "fmt"
type Vertex string
type Edge struct {
from Vertex
to Vertex
directed bool
weight int
}
type Graph struct {
vertices []Vertex
edges []Edge
}
func (g *Graph) AddVertex(v Vertex) {
g.vertices = append(g.vertices, v)
}
func (g *Graph) AddEdge(from, to Vertex, directed bool, weight int) {
edge := Edge{from: from, to: to, directed: directed, weight: weight}
g.edges = append(g.edges, edge)
if !directed {
// For undirected, add edge in both directions
edgeRev := Edge{from: to, to: from, directed: directed, weight: weight}
g.edges = append(g.edges, edgeRev)
}
}
func (g *Graph) Print() {
fmt.Println("Vertices:")
for _, v := range g.vertices {
fmt.Printf("%s ", v)
}
fmt.Println()
fmt.Println("Edges:")
for _, e := range g.edges {
arrow := "->"
if !e.directed {
arrow = "↔"
}
if e.weight > 0 {
fmt.Printf("%s %s %s (weight %d)\n", e.from, arrow, e.to, e.weight)
} else {
fmt.Printf("%s %s %s\n", e.from, arrow, e.to)
}
}
}
func main() {
g := Graph{}
g.AddVertex("A")
g.AddVertex("B")
g.AddVertex("C")
g.AddVertex("D")
g.AddEdge("A", "B", true, 0) // directed edge A->B
g.AddEdge("B", "C", false, 0) // undirected edge B<->C
g.AddEdge("C", "D", true, 5) // directed weighted edge C->D weight 5
g.Print()
}
g.AddEdge("A", "B", true, 0) // directed edge A->B
Add directed edge from A to B
g.AddEdge("B", "C", false, 0) // undirected edge B<->C
Add undirected edge between B and C by adding edges both ways
g.AddEdge("C", "D", true, 5) // directed weighted edge C->D weight 5
Add directed weighted edge from C to D with weight 5
Print all vertices and edges with direction and weight
Vertices:
A B C D
Edges:
A -> B
B ↔ C
C ↔ B
C -> D (weight 5)