Go graph programs model things that connect to each other, like cities joined by roads, users who follow users or tasks that depend on other tasks. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra.
You should first finish our Go tree programs, because a tree is a special kind of graph. You will also use a queue from the Go stack and queue programs and a heap from the Go heap programs. All programs were tested on Go 1.27.
What are Go Graph Programs?
Go graph programs work with nodes (also called vertices) and edges. An edge connects two nodes. In an undirected graph, an edge works both ways, like a two-way road. In a directed graph, an edge has one direction, like “Asha follows Ravi”.
Think of a city metro map. Each station is a node and each line between two stations is an edge. Finding the quickest route is a graph problem.
Why Go Graph Programs Matter
Graphs are everywhere in backend systems, even when nobody calls them graphs.
- Maps and delivery: shortest route between two points.
- Social apps: friend suggestions and “people you may know”.
- Build tools:
go buildcompiles packages in dependency order, which is a topological sort. - Interviews: number of islands, course schedule and shortest path are very common.
How Go Graph Programs Work
The usual way to store a graph in Go is an adjacency list. It is a map (or slice) where each node points to a slice of its neighbours. To explore the graph, you start at one node and visit neighbours, keeping a visited set so you never loop forever.

The table below compares the two ways to store a graph.
| Storage | Memory | Check if edge exists | Best for |
|---|---|---|---|
| Adjacency list | O(nodes + edges) | O(neighbours) | Most real graphs |
| Adjacency matrix | O(nodes squared) | O(1) | Small, dense graphs |
| Edge list | O(edges) | O(edges) | Sorting edges, Kruskal |
Basic Go Graph Programs
These first Go graph programs store a graph in two ways and then walk it in breadth-first and depth-first order.
Program 1: Build an Adjacency List
package main
import "fmt"
// Graph maps each city name to the list of cities it connects to.
type Graph map[string][]string
// AddEdge links a road between two cities in both directions.
func (graph Graph) AddEdge(from, to string) {
graph[from] = append(graph[from], to) // append adds an item to the end of a slice
graph[to] = append(graph[to], from) // roads go both ways
}
func main() {
graph := Graph{} // := creates the variable; Graph{} is an empty map
graph.AddEdge("Pune", "Mumbai")
graph.AddEdge("Pune", "Nashik")
graph.AddEdge("Mumbai", "Goa")
// range gives each item of the slice; we use a fixed order for printing
for _, city := range []string{"Pune", "Mumbai", "Nashik", "Goa"} {
fmt.Println(city, "->", graph[city])
}
}
Pune -> [Mumbai Nashik]
Mumbai -> [Pune Goa]
Nashik -> [Pune]
Goa -> [Mumbai]
Each call to AddEdge adds the road to both cities’ lists. We print in a fixed order because map iteration order in Go is random. The neighbour slices keep the order in which edges were added.
Program 2: Count the Neighbours of Each Node
package main
import (
"fmt"
"sort"
)
func main() {
// Each person maps to the list of their friends
friends := map[string][]string{
"Asha": {"Ravi", "Meera"},
"Ravi": {"Asha"},
"Meera": {"Asha", "Kiran"},
"Kiran": {"Meera"},
}
// Step 1: collect the names and sort them, because map order is random
var names []string
for name := range friends {
names = append(names, name)
}
sort.Strings(names)
// Step 2: the number of neighbours (the degree) is the length of the list
mostFriends := ""
for _, name := range names {
count := len(friends[name])
fmt.Println(name, "friend count:", count)
if mostFriends == "" || count > len(friends[mostFriends]) {
mostFriends = name // remember the person with the biggest list so far
}
}
fmt.Println("most friends:", mostFriends)
}
Asha friend count: 2
Kiran friend count: 1
Meera friend count: 2
Ravi friend count: 1
most friends: Asha
The number of edges on a node is called its degree. In an adjacency list, the degree is just the length of that node’s slice. We sort the names first so the output is the same on every run. Then one loop prints each count and keeps track of the biggest one.
Program 3: Store a Graph as an Adjacency Matrix
package main
import "fmt"
func main() {
// Cities are numbered 0 to 3, so we can use them as slice indexes
names := []string{"Pune", "Mumbai", "Nashik", "Goa"}
// Step 1: make a 4 by 4 grid where every cell starts as false.
// make creates a slice of the given length.
matrix := make([][]bool, len(names))
for i := range matrix {
matrix[i] = make([]bool, len(names))
}
// Step 2: add the roads. [2]int is a fixed pair of two numbers.
roads := [][2]int{{0, 1}, {0, 2}, {1, 3}}
for _, road := range roads {
matrix[road[0]][road[1]] = true
matrix[road[1]][road[0]] = true // set both cells, because roads go both ways
}
// Step 3: checking one road is a single lookup
fmt.Println(names[0], "-", names[1], matrix[0][1])
fmt.Println(names[0], "-", names[3], matrix[0][3])
fmt.Println(names[3], "-", names[1], matrix[3][1])
}
Pune - Mumbai true
Pune - Goa false
Goa - Mumbai true
This is the same road map as Program 1, stored as a grid. Cell matrix[a][b] is true when city a has a road to city b. Checking a road needs only one lookup. But the grid uses memory for every pair, even pairs with no road.
Program 4: Breadth-First Search (BFS)
package main
import "fmt"
// bfs visits nodes level by level using a queue.
func bfs(graph map[int][]int, start int) []int {
visited := map[int]bool{start: true} // a set of nodes we have already queued
queue := []int{start}
var order []int
for len(queue) > 0 {
// Step 1: take the first node out of the queue
node := queue[0]
queue = queue[1:] // [1:] keeps everything except the first item
order = append(order, node)
// Step 2: add every neighbour we have not seen yet
for _, neighbor := range graph[node] {
if !visited[neighbor] {
visited[neighbor] = true // mark when adding, so no node joins twice
queue = append(queue, neighbor)
}
}
}
return order
}
func main() {
graph := map[int][]int{
1: {2, 3},
2: {1, 4, 5},
3: {1, 6},
4: {2}, 5: {2}, 6: {3},
}
fmt.Println(bfs(graph, 1))
}
[1 2 3 4 5 6]
The queue starts with node 1. Each time you take a node out, you add its unseen neighbours to the back. BFS visits every node one step away before any node two steps away. That is why many Go graph programs use it to find the shortest path when every edge costs the same.
Program 5: Depth-First Search (DFS) with Recursion
package main
import "fmt"
// dfs goes as deep as possible along one branch before trying the next.
// order is a pointer (*[]int), so every call adds to the same slice.
func dfs(graph map[int][]int, node int, visited map[int]bool, order *[]int) {
visited[node] = true
*order = append(*order, node)
for _, neighbor := range graph[node] {
if !visited[neighbor] {
dfs(graph, neighbor, visited, order) // recursion acts as the stack
}
}
}
func main() {
graph := map[int][]int{
1: {2, 3},
2: {1, 4, 5},
3: {1, 6},
4: {2}, 5: {2}, 6: {3},
}
var order []int
dfs(graph, 1, map[int]bool{}, &order) // &order passes a pointer to the slice
fmt.Println(order)
}
[1 2 4 5 3 6]
The function marks a node, adds it to the order, and then calls itself for the first unvisited neighbour. DFS finishes the whole branch under 2 before moving to 3. Compare this order with the BFS output above.

Program 6: DFS with an Explicit Stack
package main
import "fmt"
// dfsLoop does DFS with a slice used as a stack instead of recursion.
func dfsLoop(graph map[int][]int, start int) []int {
visited := map[int]bool{}
stack := []int{start}
var order []int
for len(stack) > 0 {
// Step 1: pop the last node from the stack
node := stack[len(stack)-1]
stack = stack[:len(stack)-1] // drop the last item
if visited[node] {
continue // a node can be pushed twice, so skip repeats
}
visited[node] = true
order = append(order, node)
// Step 2: push neighbours in reverse, so the first neighbour pops first
neighbors := graph[node]
for i := len(neighbors) - 1; i >= 0; i-- {
if !visited[neighbors[i]] {
stack = append(stack, neighbors[i])
}
}
}
return order
}
func main() {
graph := map[int][]int{
1: {2, 3},
2: {1, 4, 5},
3: {1, 6},
4: {2}, 5: {2}, 6: {3},
}
fmt.Println(dfsLoop(graph, 1))
}
[1 2 4 5 3 6]
A stack gives back the last item you put in. Pushing neighbours in reverse gives the same order as the recursive version. Use this form for huge graphs where deep recursion could use too much stack.
Path and Cycle Go Graph Programs
These Go graph programs answer two common questions: how do I get from A to B, and does the graph loop back on itself?
Program 7: Shortest Path in an Unweighted Graph
package main
import (
"fmt"
"slices"
)
// shortestPath runs BFS and remembers the parent of each node,
// then walks the parents back from the end to the start.
func shortestPath(graph map[string][]string, from, to string) []string {
parent := map[string]string{from: ""} // the start node has no parent
queue := []string{from}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node == to {
break // we reached the goal
}
for _, neighbor := range graph[node] {
_, seen := parent[neighbor] // seen is true if the key is in the map
if !seen {
parent[neighbor] = node
queue = append(queue, neighbor)
}
}
}
_, found := parent[to]
if !found {
return nil // no route; nil is an empty slice here
}
// Walk back from the goal to the start using the parent map
var path []string
current := to
for current != "" {
path = append(path, current)
current = parent[current]
}
slices.Reverse(path) // we built it backwards
return path
}
func main() {
graph := map[string][]string{
"A": {"B", "C"}, "B": {"A", "D"}, "C": {"A", "D", "E"},
"D": {"B", "C", "F"}, "E": {"C", "F"}, "F": {"D", "E"},
}
fmt.Println(shortestPath(graph, "A", "F"))
fmt.Println(shortestPath(graph, "A", "Z"))
}
[A B D F]
[]
BFS reaches F first through B and D, and it saves who led to each node. The parent map does two jobs. It marks nodes as visited, and it lets us rebuild the route at the end.
Program 8: Detect a Cycle in an Undirected Graph
package main
import "fmt"
// hasCycle runs DFS. Meeting a visited node that is not our parent means a loop.
func hasCycle(graph map[int][]int, node, parent int, visited map[int]bool) bool {
visited[node] = true
for _, neighbor := range graph[node] {
if !visited[neighbor] {
if hasCycle(graph, neighbor, node, visited) {
return true
}
} else if neighbor != parent {
return true // reached an old node by a different road
}
}
return false
}
func main() {
tree := map[int][]int{1: {2, 3}, 2: {1}, 3: {1}}
loop := map[int][]int{1: {2, 3}, 2: {1, 3}, 3: {1, 2}} // triangle
// -1 means "no parent", because node 1 is where we start
fmt.Println(hasCycle(tree, 1, -1, map[int]bool{}))
fmt.Println(hasCycle(loop, 1, -1, map[int]bool{}))
}
false
true
Each call remembers which node it came from. In an undirected graph, the edge back to your parent is not a cycle. Any other visited neighbour is.
Program 9: Detect a Cycle in a Directed Graph
package main
import "fmt"
// Three colours for each node. iota counts up: white = 0, grey = 1, black = 2.
const (
white = iota // not visited
grey // on the current DFS path
black // fully done
)
// isCyclic reports whether DFS from node ever loops back onto its own path.
func isCyclic(graph map[string][]string, node string, color map[string]int) bool {
color[node] = grey
for _, neighbor := range graph[node] {
if color[neighbor] == grey {
return true // neighbor is still on our path, so we looped back
}
if color[neighbor] == white && isCyclic(graph, neighbor, color) {
return true
}
}
color[node] = black // every path from here is finished
return false
}
func main() {
safe := map[string][]string{"api": {"db", "cache"}, "cache": {"db"}}
broken := map[string][]string{"a": {"b"}, "b": {"c"}, "c": {"a"}}
fmt.Println(isCyclic(safe, "api", map[string]int{}))
fmt.Println(isCyclic(broken, "a", map[string]int{}))
}
false
true
A missing key in the color map reads as 0, which is white. Grey means “on the path right now”. Reaching a black node is fine, because that branch already finished without a loop. This is how Go reports an “import cycle not allowed” error.
Most Asked Interview Go Graph Programs
These Go graph programs cover the questions you are most likely to meet in a coding round.
Program 10: Topological Sort (Course Schedule)
package main
import "fmt"
// topoSort uses Kahn's method: repeatedly take a node with no
// remaining prerequisites (in-degree 0).
func topoSort(total int, prerequisites [][2]int) ([]int, bool) {
// Step 1: build the graph and count incoming edges for each node
nextCourses := make([][]int, total)
inDegree := make([]int, total)
for _, pair := range prerequisites { // pair[0] must come before pair[1]
nextCourses[pair[0]] = append(nextCourses[pair[0]], pair[1])
inDegree[pair[1]]++
}
// Step 2: start with every node that has no prerequisites
var queue, order []int
for i := 0; i < total; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
// Step 3: take a ready node, then free up the nodes that depend on it
for len(queue) > 0 {
course := queue[0]
queue = queue[1:]
order = append(order, course)
for _, next := range nextCourses[course] {
inDegree[next]-- // one prerequisite is now done
if inDegree[next] == 0 {
queue = append(queue, next)
}
}
}
return order, len(order) == total // if some are left, there is a cycle
}
func main() {
// 0 Go basics, 1 Functions, 2 Structs, 3 Interfaces
fmt.Println(topoSort(4, [][2]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}}))
fmt.Println(topoSort(2, [][2]int{{0, 1}, {1, 0}}))
}
[0 1 2 3] true
[] false
The in-degree of a node is how many prerequisites it still waits for. Nodes with in-degree 0 are ready, so they go into the queue. If a cycle exists, some nodes never reach in-degree 0, so the order is shorter than total. That answers “can you finish all courses?” too.
Program 11: Count Connected Components
package main
import "fmt"
// visit marks node and every node it can reach.
func visit(neighbors [][]int, visited []bool, node int) {
visited[node] = true
for _, next := range neighbors[node] {
if !visited[next] {
visit(neighbors, visited, next)
}
}
}
// components counts groups of nodes that can reach each other.
func components(total int, edges [][2]int) int {
// Step 1: build the adjacency list, both directions
neighbors := make([][]int, total)
for _, edge := range edges {
neighbors[edge[0]] = append(neighbors[edge[0]], edge[1])
neighbors[edge[1]] = append(neighbors[edge[1]], edge[0])
}
// Step 2: every unvisited node starts a new group
visited := make([]bool, total)
count := 0
for node := 0; node < total; node++ {
if !visited[node] {
count++ // a new group starts here
visit(neighbors, visited, node) // mark the whole group
}
}
return count
}
func main() {
fmt.Println(components(6, [][2]int{{0, 1}, {1, 2}, {3, 4}}))
}
3
The loop checks nodes 0 to 5 in order. When it finds an unvisited node, it adds 1 to the count and marks that whole group. The groups are {0, 1, 2}, {3, 4} and {5}, and this counting loop appears in many Go graph programs. Node 5 has no edges, but it still counts as its own group.
Program 12: Number of Islands
package main
import "fmt"
// sink turns a land cell and all land joined to it into water.
func sink(grid [][]byte, row, col int) {
if row < 0 || col < 0 || row >= len(grid) || col >= len(grid[0]) {
return // outside the grid
}
if grid[row][col] != '1' {
return // water or already visited
}
grid[row][col] = '0' // sink this land so we never count it again
sink(grid, row+1, col) // down
sink(grid, row-1, col) // up
sink(grid, row, col+1) // right
sink(grid, row, col-1) // left
}
// islands counts groups of '1' cells joined up, down, left or right.
func islands(grid [][]byte) int {
count := 0
for row := 0; row < len(grid); row++ {
for col := 0; col < len(grid[0]); col++ {
if grid[row][col] == '1' {
count++ // found a new island
sink(grid, row, col)
}
}
}
return count
}
func main() {
// []byte("11000") turns the text into a slice of characters
grid := [][]byte{
[]byte("11000"),
[]byte("11000"),
[]byte("00100"),
[]byte("00011"),
}
fmt.Println(islands(grid))
}
3
A grid is a graph where each cell links to its four neighbours. The loop finds a land cell, counts it, and sink wipes out the rest of that island. Changing visited land to ‘0’ saves a separate visited set, but it changes the input, so mention that in an interview.
Program 13: Rotting Oranges with Multi-Source BFS
package main
import "fmt"
// cell is one position in the grid.
type cell struct{ row, col int }
// isFresh reports whether the position is inside the grid and holds a fresh orange.
func isFresh(grid [][]int, row, col int) bool {
if row < 0 || col < 0 || row >= len(grid) || col >= len(grid[0]) {
return false
}
return grid[row][col] == 1
}
// minutesToRot returns how long until every fresh orange (1) is rotten,
// when each rotten orange (2) spreads to its neighbours every minute.
func minutesToRot(grid [][]int) int {
// Step 1: put all rotten oranges in the queue and count the fresh ones
var queue []cell
fresh := 0
for row := range grid {
for col := range grid[row] {
if grid[row][col] == 2 {
queue = append(queue, cell{row, col})
} else if grid[row][col] == 1 {
fresh++
}
}
}
// Step 2: one round of the loop is one minute (one BFS level)
directions := []cell{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
minutes := 0
for len(queue) > 0 && fresh > 0 {
size := len(queue)
for i := 0; i < size; i++ {
current := queue[0]
queue = queue[1:]
for _, step := range directions {
row := current.row + step.row
col := current.col + step.col
if isFresh(grid, row, col) {
grid[row][col] = 2 // it rots now
fresh--
queue = append(queue, cell{row, col})
}
}
}
minutes++
}
if fresh > 0 {
return -1 // some oranges can never be reached
}
return minutes
}
func main() {
fmt.Println(minutesToRot([][]int{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}}))
fmt.Println(minutesToRot([][]int{{2, 1, 1}, {0, 1, 1}, {1, 0, 1}}))
}
4
-1
All rotten oranges go into the queue before the loop starts. Each round rots the fresh neighbours of the current queue, and that round counts as one minute. Starting BFS from all rotten oranges at once is called multi-source BFS. The same idea finds the nearest hospital from every house.
Program 14: Dijkstra’s Shortest Path with Weights
package main
import (
"container/heap"
"fmt"
)
// road is a one-way link to another place with a cost.
type road struct {
to string
cost int
}
// item is a place and the best distance found to it so far.
type item struct {
place string
distance int
}
// minHeap keeps the item with the smallest distance on top.
// These five methods are what container/heap needs.
type minHeap []item
func (items minHeap) Len() int { return len(items) }
func (items minHeap) Less(i, j int) bool { return items[i].distance < items[j].distance }
func (items minHeap) Swap(i, j int) { items[i], items[j] = items[j], items[i] } // swap two items
func (items *minHeap) Push(value any) { *items = append(*items, value.(item)) } // .(item) gets the item back from any
func (items *minHeap) Pop() any {
old := *items
last := old[len(old)-1]
*items = old[:len(old)-1]
return last
}
// dijkstra always finishes the closest unfinished place next.
func dijkstra(graph map[string][]road, start string) map[string]int {
best := map[string]int{start: 0}
queue := &minHeap{{start, 0}}
for queue.Len() > 0 {
current := heap.Pop(queue).(item) // the closest place left
if current.distance > best[current.place] {
continue // an old, longer entry: skip it
}
for _, next := range graph[current.place] {
newDistance := current.distance + next.cost
oldDistance, ok := best[next.to] // ok is true if we already have a distance
if !ok || newDistance < oldDistance {
best[next.to] = newDistance // found a shorter route
heap.Push(queue, item{next.to, newDistance})
}
}
}
return best
}
func main() {
graph := map[string][]road{
"Home": {{"Market", 4}, {"School", 1}},
"School": {{"Market", 2}, {"Office", 6}},
"Market": {{"Office", 3}},
}
distances := dijkstra(graph, "Home")
for _, place := range []string{"Home", "School", "Market", "Office"} {
fmt.Println(place, distances[place])
}
}
Home 0
School 1
Market 3
Office 6
The heap always gives back the place with the smallest distance so far. For each road out of that place, you check if it gives a shorter route and save it. Going Home to School to Market costs 3, which beats the direct road of 4. Weighted Go graph programs, like maps and delivery apps, depend on this. Dijkstra works only when no edge has a negative cost.
BFS vs DFS in Go Graph Programs
Both visit every reachable node once, but they explore in different orders. The table below compares them.
| Feature | BFS | DFS |
|---|---|---|
| Uses | A queue | A stack or recursion |
| Order | Level by level | One branch to the end |
| Shortest path (equal costs) | Yes | No |
| Memory | Can be large for wide graphs | Can be large for deep graphs |
| Good for | Shortest path, nearest item | Cycles, topological sort, islands |
A simple rule helps: if the question says “shortest” or “minimum steps”, use BFS. If it says “all paths”, “cycle” or “connected”, DFS is usually simpler.
Common Mistakes in Go Graph Programs
- No visited set: the search loops forever on any cycle.
- Marking visited too late in BFS: mark when you add to the queue, not when you remove.
- Relying on map order: Go map order is random, so sort keys or use slices for stable output.
- Treating the parent edge as a cycle: in undirected graphs, skip the node you came from.
- Using Dijkstra with negative costs: use Bellman-Ford instead.
Best Practices for Go Graph Programs
- Number your nodes 0 to n-1 and use slices, which are faster than maps.
- Keep a parent map whenever you may need the actual path.
- Use a heap for weighted shortest paths, and plain BFS for equal costs.
- Check grid bounds first before reading a cell.
- Draw the graph on paper and trace the queue or stack by hand.
Go Graph Programs Interview Questions and Answers
These are the graph questions interviewers ask most, and they build on the Go graph programs above. Each code answer is complete, with real output from Go 1.27.
Concept Questions on Go Graph Programs
Q1. What is the time complexity of BFS and DFS?
Both are O(V + E), where V is the number of nodes and E is the number of edges. Each node is visited once, and each edge is checked once or twice.
Q2. What is the difference between a tree and a graph?
A tree is a connected graph with no cycles and exactly V – 1 edges. A general graph can have cycles, many separate parts and any number of edges.
Q3. What is a DAG?
A directed acyclic graph has one-way edges and no cycles. Task dependencies and Go package imports form DAGs, which is why they can be topologically sorted.
Q4. What does this program print?
package main
import "fmt"
func main() {
// in-degree: how many edges point INTO each node
edges := [][2]int{{0, 1}, {0, 2}, {1, 2}, {3, 2}}
inDegree := make([]int, 4) // four counters, all starting at 0
for _, edge := range edges {
inDegree[edge[1]]++ // edge[1] is the node the edge points to
}
fmt.Println(inDegree)
}
[0 1 3 0]
Node 2 has three edges pointing into it. Nodes 0 and 3 have none, so they could be done first in a topological sort.
Coding Questions
Q5. How do you check if a path exists between two nodes?
package main
import "fmt"
// hasPath runs DFS with a stack and stops as soon as it reaches to.
func hasPath(graph [][]int, from, to int) bool {
visited := make([]bool, len(graph))
stack := []int{from}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if node == to {
return true
}
if visited[node] {
continue
}
visited[node] = true
stack = append(stack, graph[node]...) // ... adds every neighbour at once
}
return false
}
func main() {
graph := [][]int{{1}, {0, 2}, {1}, {4}, {3}}
fmt.Println(hasPath(graph, 0, 2), hasPath(graph, 0, 4))
}
true false
The search starts at from and keeps visiting neighbours until the stack is empty. Nodes 3 and 4 form a separate group, so there is no way to reach 4 from 0.
Q6. How do you check if a graph can be coloured with two colours?
package main
import "fmt"
// bipartite tries to colour neighbours with opposite colours using BFS.
func bipartite(graph [][]int) bool {
color := make([]int, len(graph)) // 0 = none, 1 and -1 are the two colours
for start := range graph {
if color[start] != 0 {
continue // already coloured from an earlier start
}
color[start] = 1
queue := []int{start}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
for _, neighbor := range graph[node] {
if color[neighbor] == 0 {
color[neighbor] = -color[node] // give the opposite colour
queue = append(queue, neighbor)
} else if color[neighbor] == color[node] {
return false // two neighbours share a colour
}
}
}
}
return true
}
func main() {
square := [][]int{{1, 3}, {0, 2}, {1, 3}, {0, 2}}
triangle := [][]int{{1, 2}, {0, 2}, {0, 1}}
fmt.Println(bipartite(square), bipartite(triangle))
}
true false
Each node gives its neighbours the opposite colour. If a neighbour already has the same colour, the check fails. A graph with an odd-length cycle, like a triangle, can never be split into two groups this way.
Q7. How do you clone a graph?
Walk it with BFS or DFS and keep a map from each old node to its new copy. When you meet a neighbour, create its copy only if the map does not already have it, then link the copies.
Design Questions
Q8. How would you find “people you may know” in a social app?
Run BFS from the user for two levels. Friends of friends who are not already friends are the suggestions, ranked by how many mutual friends they share.
Q9. Why does Go refuse import cycles?
Packages are compiled and initialised in dependency order, which needs a DAG. A cycle has no valid order, so the compiler stops with “import cycle not allowed”.
Q10. When would you use an adjacency matrix?
Use one for small, dense graphs, such as 100 cities where nearly every pair has a road. It checks if an edge exists in O(1), but it uses O(V squared) memory.
Practice Task
To practise Go graph programs, solve “word ladder”: change “cold” into “warm” one letter at a time, where every middle word must be in a list like cord, card, ward, warm, worm, word. Print the fewest steps. Hint: each word is a node, and BFS finds the shortest route.
Official Resources
Quick Recap
- Go graph programs store nodes and edges, usually as an adjacency list.
- BFS uses a queue and finds the shortest path when edges cost the same.
- DFS uses recursion or a stack and is great for cycles and islands.
- Topological sort orders tasks with dependencies and spots cycles.
- Dijkstra with a heap finds the cheapest route when edges have weights.
What’s Next?
Next, we put every level of this series together with the coding questions companies ask most. Read Go coding interview programs, with LRU cache, sliding window, two pointers and dynamic programming. For more practice, see the Go tree programs.


