To implement a graph data structure using a map in Go, you can use an adjacency list representation, where each vertex is represented by a key in the map, and its corresponding value is a list of its adjacent vertices. Follow these steps to implement it:
Step 1: Define the Graph struct:
type Graph struct {
vertices map[int][]int
}
Step 2: Create a NewGraph function to initialize a new graph:
func NewGraph() *Graph {
return &Graph{vertices: make(map[int][]int)}
}
Step 3: Implement the AddVertex method to add a new vertex to the graph:
func (g *Graph) AddVertex(vertex int) {
g.vertices[vertex] = []int{}
}
Step 4: Implement the AddEdge method to add an edge between two vertices:
func (g *Graph) AddEdge(src, dest int) {
g.vertices[src] = append(g.vertices[src], dest)
g.vertices[dest] = append(g.vertices[dest], src)
}
Step 5: Implement the GetAdjacentVertices method to retrieve the adjacent vertices of a given vertex:
func (g *Graph) GetAdjacentVertices(vertex int) []int {
return g.vertices[vertex]
}
Step 6: Implement the main function to create a new graph, add vertices, and edges:
func main() {
g := NewGraph()
// Add vertices
g.AddVertex(1)
g.AddVertex(2)
g.AddVertex(3)
// Add edges
g.AddEdge(1, 2)
g.AddEdge(2, 3)
// Retrieve adjacent vertices
adjacent := g.GetAdjacentVertices(2)
fmt.Println("Adjacent vertices of 2:", adjacent)
}
In this example, we create a graph with three vertices (1, 2, 3) and add two edges (1->2 and 2->3). Finally, we retrieve the adjacent vertices of vertex 2 and print them.