An adjacency list is efficient for sparse graphs because it stores only existing edges, saving memory and speeding up iteration over neighbors.
An adjacency matrix allows O(1) time to check if an edge exists between any two nodes, which is useful for dense graphs or frequent edge queries.
package main import "fmt" func main() { matrix := [][]int{ {0,1,0}, {1,0,1}, {0,1,0}, } adjList := make([][]int, len(matrix)) for i := range matrix { for j, val := range matrix[i] { if val == 1 { adjList[i] = append(adjList[i], j) } } } fmt.Println(adjList) }
The code appends indices of columns with value 1 for each row, creating adjacency lists: node 0 connects to 1, node 1 connects to 0 and 2, node 2 connects to 1.
package main import "fmt" func main() { matrix := [][]int{ {0,1,0}, {1,0,1}, {0,1,0}, } fmt.Println(matrix[1][3] == 1) }
Accessing matrix[1][3] is invalid because the inner slice has length 3 with indices 0,1,2 only, causing an index out of range runtime error.
In a large sparse graph like a social network, adjacency lists save memory by storing only actual connections. Adjacency matrices waste memory and are inefficient.
