A graph algorithm is a set of instructions for solving problems related to graphs, which are mathematical structures consisting of vertices (nodes) and edges (connections between vertices). Graph algorithms are used to analyze and manipulate data represented in the form of graphs.
Here's an example of a simple graph algorithm in Go, which finds the shortest path between two vertices in a graph using Dijkstra's algorithm:
package main
import (
"fmt"
"math"
)
type Graph struct {
vertices map[string]map[string]int
}
func NewGraph() *Graph {
return &Graph{vertices: make(map[string]map[string]int)}
}
func (g *Graph) AddVertex(vertex string) {
if _, ok := g.vertices[vertex]; !ok {
g.vertices[vertex] = make(map[string]int)
}
}
func (g *Graph) AddEdge(from, to string, weight int) {
g.vertices[from][to] = weight
g.vertices[to][from] = weight
}
func (g *Graph) Dijkstra(start string) map[string]int {
distances := make(map[string]int)
visited := make(map[string]bool)
for vertex := range g.vertices {
distances[vertex] = math.MaxInt32
visited[vertex] = false
}
distances[start] = 0
for i := 0; i < len(g.vertices); i++ {
u := minDistance(distances, visited)
visited[u] = true
for v := range g.vertices[u] {
if !visited[v] && distances[u]+g.vertices[u][v] < distances[v] {
distances[v] = distances[u] + g.vertices[u][v]
}
}
}
return distances
}
func minDistance(distances map[string]int, visited map[string]bool) string {
minDist := math.MaxInt32
minVertex := ""
for vertex, dist := range distances {
if !visited[vertex] && dist <= minDist {
minDist = dist
minVertex = vertex
}
}
return minVertex
}
func main() {
g := NewGraph()
g.AddVertex("A")
g.AddVertex("B")
g.AddVertex("C")
g.AddVertex("D")
g.AddEdge("A", "B", 5)
g.AddEdge("A", "C", 3)
g.AddEdge("B", "D", 4)
g.AddEdge("C", "D", 7)
distances := g.Dijkstra("A")
fmt.Println("Shortest distances:", distances)
}
In this example, we create a graph, add vertices and edges, and then use the Dijkstra algorithm to find the shortest path from a specified starting vertex to all other vertices in the graph.