package main
import "fmt"
// Graph using adjacency list
type GraphList struct {
adj map[int][]int
}
func NewGraphList() *GraphList {
return &GraphList{adj: make(map[int][]int)}
}
func (g *GraphList) AddEdge(u, v int) {
// add v to u's list
g.adj[u] = append(g.adj[u], v)
// add u to v's list (undirected)
g.adj[v] = append(g.adj[v], u)
}
func (g *GraphList) HasEdge(u, v int) bool {
// scan neighbors of u
for _, nbr := range g.adj[u] {
if nbr == v {
return true
}
}
return false
}
func (g *GraphList) String() string {
res := ""
for node := 1; node <= 4; node++ {
res += fmt.Sprintf("Node %d ->", node)
for _, nbr := range g.adj[node] {
res += fmt.Sprintf(" %d ->", nbr)
}
res += " null\n"
}
return res
}
// Graph using adjacency matrix
type GraphMatrix struct {
matrix [][]int
size int
}
func NewGraphMatrix(size int) *GraphMatrix {
m := make([][]int, size)
for i := range m {
m[i] = make([]int, size)
}
return &GraphMatrix{matrix: m, size: size}
}
func (g *GraphMatrix) AddEdge(u, v int) {
// mark edge in matrix (undirected)
g.matrix[u-1][v-1] = 1
g.matrix[v-1][u-1] = 1
}
func (g *GraphMatrix) HasEdge(u, v int) bool {
return g.matrix[u-1][v-1] == 1
}
func (g *GraphMatrix) String() string {
res := " 1 2 3 4\n"
for i := 0; i < g.size; i++ {
res += fmt.Sprintf("%d [", i+1)
for j := 0; j < g.size; j++ {
res += fmt.Sprintf(" %d", g.matrix[i][j])
}
res += " ]\n"
}
return res
}
func main() {
// Create graph with edges 1-2, 1-4, 2-3
gl := NewGraphList()
gl.AddEdge(1, 2)
gl.AddEdge(1, 4)
gl.AddEdge(2, 3)
gm := NewGraphMatrix(4)
gm.AddEdge(1, 2)
gm.AddEdge(1, 4)
gm.AddEdge(2, 3)
// Check edge 1-3
fmt.Printf("Edge 1-3 in list? %v\n", gl.HasEdge(1, 3))
fmt.Printf("Edge 1-3 in matrix? %v\n", gm.HasEdge(1, 3))
// Add edge 3-4
gl.AddEdge(3, 4)
gm.AddEdge(3, 4)
// Print final graphs
fmt.Println("Adjacency List:")
fmt.Print(gl.String())
fmt.Println("Adjacency Matrix:")
fmt.Print(gm.String())
}
g.adj[u] = append(g.adj[u], v)
// add neighbor v to node u's adjacency list
add neighbor v to node u's adjacency list
g.adj[v] = append(g.adj[v], u)
// add u to v's list (undirected)
add neighbor u to node v's adjacency list for undirected edge
for _, nbr := range g.adj[u] {
if nbr == v {
return true
}
}
scan neighbors of u to check if v is connected
g.matrix[u-1][v-1] = 1
// mark edge in matrix (undirected)
set matrix cell to 1 to mark edge from u to v
g.matrix[v-1][u-1] = 1
// mark edge in matrix (undirected)
set matrix cell to 1 to mark edge from v to u
return g.matrix[u-1][v-1] == 1
directly check if edge exists in matrix
Edge 1-3 in list? false
Edge 1-3 in matrix? false
Adjacency List:
Node 1 -> 2 -> 4 -> null
Node 2 -> 1 -> 3 -> null
Node 3 -> 2 -> 4 -> null
Node 4 -> 1 -> 3 -> null
Adjacency Matrix:
1 2 3 4
1 [ 0 1 0 1 ]
2 [ 1 0 1 0 ]
3 [ 0 1 0 1 ]
4 [ 1 0 1 0 ]