A graph algorithm is a set of steps or instructions designed to find a solution or perform an operation on a graph data structure. A graph is a collection of nodes (also called vertices) connected by edges. Graphs are used to model and solve complex problems in various fields, such as computer networks, social networks, optimization, and routing problems.
A graph algorithm typically involves visiting and processing each node and edge in the graph. The algorithm may perform different operations, such as searching for a specific node or path, computing shortest paths, or finding the minimum spanning tree.
Here is an example of a simple graph algorithm called Depth-First Search (DFS) implemented in Go:
package main
import (
"fmt"
)
// Graph represents a directed graph with adjacency lists
type Graph struct {
nodes map[int][]int
}
// NewGraph creates a new directed graph
func NewGraph() *Graph {
return &Graph{nodes: make(map[int][]int)}
}
// AddNode adds a new node to the graph
func (g *Graph) AddNode(node int) {
g.nodes[node] = []int{}
}
// AddEdge adds a directed edge from src to dst
func (g *Graph) AddEdge(src, dst int) {
g.nodes[src] = append(g.nodes[src], dst)
}
// DFS performs a depth-first search of the graph starting from the given node
func (g *Graph) DFS(start int) {
visited := make(map[int]bool)
stack := []int{start}
for len(stack) > 0 {
current := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if !visited[current] {
visited[current] = true
fmt.Printf("Visited node: %d\n", current)
for _, neighbor := range g.nodes[current] {
stack = append(stack, neighbor)
}
}
}
}
func main() {
g := NewGraph()
g.AddNode(1)
g.AddNode(2)
g.AddNode(3)
g.AddNode(4)
g.AddEdge(1, 2)
g.AddEdge(1, 3)
g.AddEdge(2, 4)
g.AddEdge(3, 4)
g.DFS(1)
}
In this example, we define a directed graph with adjacency lists and implement the Depth-First Search (DFS) algorithm. The algorithm uses a stack to keep track of nodes to visit and a visited set to avoid revisiting nodes. The algorithm starts from a given node and explores as far as possible along each branch before backtracking. The example outputs the following:
Visited node: 1
Visited node: 2
Visited node: 4
Visited node: 3