{"id":858,"date":"2026-10-10T17:00:00","date_gmt":"2026-10-10T11:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/"},"modified":"2026-11-29T01:29:24","modified_gmt":"2026-11-28T19:59:24","slug":"go-graph-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/","title":{"rendered":"Go Graph Programs: BFS, DFS, Topological Sort and Dijkstra"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You should first finish our <a href=\"https:\/\/smitabharat.com\/blog\/go-tree-programs\/\">Go tree programs<\/a>, because a tree is a special kind of graph. You will also use a queue from the <a href=\"https:\/\/smitabharat.com\/blog\/go-stack-and-queue-programs\/\">Go stack and queue programs<\/a> and a heap from the <a href=\"https:\/\/smitabharat.com\/blog\/go-heap-programs\/\">Go heap programs<\/a>. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go Graph Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 &#8220;Asha follows Ravi&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go Graph Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Graphs are everywhere in backend systems, even when nobody calls them graphs.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Maps and delivery:<\/strong> shortest route between two points.<\/li>\n\n\n<li><strong>Social apps:<\/strong> friend suggestions and &#8220;people you may know&#8221;.<\/li>\n\n\n<li><strong>Build tools:<\/strong> <code>go build<\/code> compiles packages in dependency order, which is a topological sort.<\/li>\n\n\n<li><strong>Interviews:<\/strong> number of islands, course schedule and shortest path are very common.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Graph Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>visited<\/code> set so you never loop forever.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-1-1024x640.png\" alt=\"Go graph programs diagram showing a small graph and its adjacency list\" class=\"wp-image-856\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Each node lists its neighbours, and a visited set stops the search from going round in circles.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below compares the two ways to store a graph.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Storage<\/th><th>Memory<\/th><th>Check if edge exists<\/th><th>Best for<\/th><\/tr><\/thead><tbody><tr><td>Adjacency list<\/td><td>O(nodes + edges)<\/td><td>O(neighbours)<\/td><td>Most real graphs<\/td><\/tr><tr><td>Adjacency matrix<\/td><td>O(nodes squared)<\/td><td>O(1)<\/td><td>Small, dense graphs<\/td><\/tr><tr><td>Edge list<\/td><td>O(edges)<\/td><td>O(edges)<\/td><td>Sorting edges, Kruskal<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Go Graph Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go graph programs store a graph in two ways and then walk it in breadth-first and depth-first order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: Build an Adjacency List<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Graph maps each city name to the list of cities it connects to.\ntype Graph map[string][]string\n\n\/\/ AddEdge links a road between two cities in both directions.\nfunc (graph Graph) AddEdge(from, to string) {\n    graph[from] = append(graph[from], to) \/\/ append adds an item to the end of a slice\n    graph[to] = append(graph[to], from)   \/\/ roads go both ways\n}\n\nfunc main() {\n    graph := Graph{} \/\/ := creates the variable; Graph{} is an empty map\n    graph.AddEdge(\"Pune\", \"Mumbai\")\n    graph.AddEdge(\"Pune\", \"Nashik\")\n    graph.AddEdge(\"Mumbai\", \"Goa\")\n\n    \/\/ range gives each item of the slice; we use a fixed order for printing\n    for _, city := range []string{\"Pune\", \"Mumbai\", \"Nashik\", \"Goa\"} {\n        fmt.Println(city, \"-&gt;\", graph[city])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Pune -&gt; [Mumbai Nashik]\nMumbai -&gt; [Pune Goa]\nNashik -&gt; [Pune]\nGoa -&gt; [Mumbai]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each call to <code>AddEdge<\/code> adds the road to both cities&#8217; 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: Count the Neighbours of Each Node<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    \/\/ Each person maps to the list of their friends\n    friends := map[string][]string{\n        \"Asha\":  {\"Ravi\", \"Meera\"},\n        \"Ravi\":  {\"Asha\"},\n        \"Meera\": {\"Asha\", \"Kiran\"},\n        \"Kiran\": {\"Meera\"},\n    }\n\n    \/\/ Step 1: collect the names and sort them, because map order is random\n    var names []string\n    for name := range friends {\n        names = append(names, name)\n    }\n    sort.Strings(names)\n\n    \/\/ Step 2: the number of neighbours (the degree) is the length of the list\n    mostFriends := \"\"\n    for _, name := range names {\n        count := len(friends[name])\n        fmt.Println(name, \"friend count:\", count)\n        if mostFriends == \"\" || count &gt; len(friends[mostFriends]) {\n            mostFriends = name \/\/ remember the person with the biggest list so far\n        }\n    }\n    fmt.Println(\"most friends:\", mostFriends)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha friend count: 2\nKiran friend count: 1\nMeera friend count: 2\nRavi friend count: 1\nmost friends: Asha<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The number of edges on a node is called its degree. In an adjacency list, the degree is just the length of that node&#8217;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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Store a Graph as an Adjacency Matrix<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ Cities are numbered 0 to 3, so we can use them as slice indexes\n    names := []string{\"Pune\", \"Mumbai\", \"Nashik\", \"Goa\"}\n\n    \/\/ Step 1: make a 4 by 4 grid where every cell starts as false.\n    \/\/ make creates a slice of the given length.\n    matrix := make([][]bool, len(names))\n    for i := range matrix {\n        matrix[i] = make([]bool, len(names))\n    }\n\n    \/\/ Step 2: add the roads. [2]int is a fixed pair of two numbers.\n    roads := [][2]int{{0, 1}, {0, 2}, {1, 3}}\n    for _, road := range roads {\n        matrix[road[0]][road[1]] = true\n        matrix[road[1]][road[0]] = true \/\/ set both cells, because roads go both ways\n    }\n\n    \/\/ Step 3: checking one road is a single lookup\n    fmt.Println(names[0], \"-\", names[1], matrix[0][1])\n    fmt.Println(names[0], \"-\", names[3], matrix[0][3])\n    fmt.Println(names[3], \"-\", names[1], matrix[3][1])\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Pune - Mumbai true\nPune - Goa false\nGoa - Mumbai true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is the same road map as Program 1, stored as a grid. Cell <code>matrix[a][b]<\/code> is true when city <code>a<\/code> has a road to city <code>b<\/code>. Checking a road needs only one lookup. But the grid uses memory for every pair, even pairs with no road.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Breadth-First Search (BFS)<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ bfs visits nodes level by level using a queue.\nfunc bfs(graph map[int][]int, start int) []int {\n    visited := map[int]bool{start: true} \/\/ a set of nodes we have already queued\n    queue := []int{start}\n    var order []int\n    for len(queue) &gt; 0 {\n        \/\/ Step 1: take the first node out of the queue\n        node := queue[0]\n        queue = queue[1:] \/\/ [1:] keeps everything except the first item\n        order = append(order, node)\n        \/\/ Step 2: add every neighbour we have not seen yet\n        for _, neighbor := range graph[node] {\n            if !visited[neighbor] {\n                visited[neighbor] = true \/\/ mark when adding, so no node joins twice\n                queue = append(queue, neighbor)\n            }\n        }\n    }\n    return order\n}\n\nfunc main() {\n    graph := map[int][]int{\n        1: {2, 3},\n        2: {1, 4, 5},\n        3: {1, 6},\n        4: {2}, 5: {2}, 6: {3},\n    }\n    fmt.Println(bfs(graph, 1))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 2 3 4 5 6]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: Depth-First Search (DFS) with Recursion<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ dfs goes as deep as possible along one branch before trying the next.\n\/\/ order is a pointer (*[]int), so every call adds to the same slice.\nfunc dfs(graph map[int][]int, node int, visited map[int]bool, order *[]int) {\n    visited[node] = true\n    *order = append(*order, node)\n    for _, neighbor := range graph[node] {\n        if !visited[neighbor] {\n            dfs(graph, neighbor, visited, order) \/\/ recursion acts as the stack\n        }\n    }\n}\n\nfunc main() {\n    graph := map[int][]int{\n        1: {2, 3},\n        2: {1, 4, 5},\n        3: {1, 6},\n        4: {2}, 5: {2}, 6: {3},\n    }\n    var order []int\n    dfs(graph, 1, map[int]bool{}, &amp;order) \/\/ &amp;order passes a pointer to the slice\n    fmt.Println(order)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 2 4 5 3 6]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-2-1024x640.png\" alt=\"Go graph programs comparison of BFS and DFS visit order\" class=\"wp-image-857\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">BFS spreads out level by level with a queue, while DFS follows one branch to the end with a stack.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: DFS with an Explicit Stack<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ dfsLoop does DFS with a slice used as a stack instead of recursion.\nfunc dfsLoop(graph map[int][]int, start int) []int {\n    visited := map[int]bool{}\n    stack := []int{start}\n    var order []int\n    for len(stack) &gt; 0 {\n        \/\/ Step 1: pop the last node from the stack\n        node := stack[len(stack)-1]\n        stack = stack[:len(stack)-1] \/\/ drop the last item\n        if visited[node] {\n            continue \/\/ a node can be pushed twice, so skip repeats\n        }\n        visited[node] = true\n        order = append(order, node)\n        \/\/ Step 2: push neighbours in reverse, so the first neighbour pops first\n        neighbors := graph[node]\n        for i := len(neighbors) - 1; i &gt;= 0; i-- {\n            if !visited[neighbors[i]] {\n                stack = append(stack, neighbors[i])\n            }\n        }\n    }\n    return order\n}\n\nfunc main() {\n    graph := map[int][]int{\n        1: {2, 3},\n        2: {1, 4, 5},\n        3: {1, 6},\n        4: {2}, 5: {2}, 6: {3},\n    }\n    fmt.Println(dfsLoop(graph, 1))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 2 4 5 3 6]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Path and Cycle Go Graph Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go graph programs answer two common questions: how do I get from A to B, and does the graph loop back on itself?<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: Shortest Path in an Unweighted Graph<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"slices\"\n)\n\n\/\/ shortestPath runs BFS and remembers the parent of each node,\n\/\/ then walks the parents back from the end to the start.\nfunc shortestPath(graph map[string][]string, from, to string) []string {\n    parent := map[string]string{from: \"\"} \/\/ the start node has no parent\n    queue := []string{from}\n    for len(queue) &gt; 0 {\n        node := queue[0]\n        queue = queue[1:]\n        if node == to {\n            break \/\/ we reached the goal\n        }\n        for _, neighbor := range graph[node] {\n            _, seen := parent[neighbor] \/\/ seen is true if the key is in the map\n            if !seen {\n                parent[neighbor] = node\n                queue = append(queue, neighbor)\n            }\n        }\n    }\n    _, found := parent[to]\n    if !found {\n        return nil \/\/ no route; nil is an empty slice here\n    }\n    \/\/ Walk back from the goal to the start using the parent map\n    var path []string\n    current := to\n    for current != \"\" {\n        path = append(path, current)\n        current = parent[current]\n    }\n    slices.Reverse(path) \/\/ we built it backwards\n    return path\n}\n\nfunc main() {\n    graph := map[string][]string{\n        \"A\": {\"B\", \"C\"}, \"B\": {\"A\", \"D\"}, \"C\": {\"A\", \"D\", \"E\"},\n        \"D\": {\"B\", \"C\", \"F\"}, \"E\": {\"C\", \"F\"}, \"F\": {\"D\", \"E\"},\n    }\n    fmt.Println(shortestPath(graph, \"A\", \"F\"))\n    fmt.Println(shortestPath(graph, \"A\", \"Z\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[A B D F]\n[]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">BFS reaches F first through B and D, and it saves who led to each node. The <code>parent<\/code> map does two jobs. It marks nodes as visited, and it lets us rebuild the route at the end.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: Detect a Cycle in an Undirected Graph<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ hasCycle runs DFS. Meeting a visited node that is not our parent means a loop.\nfunc hasCycle(graph map[int][]int, node, parent int, visited map[int]bool) bool {\n    visited[node] = true\n    for _, neighbor := range graph[node] {\n        if !visited[neighbor] {\n            if hasCycle(graph, neighbor, node, visited) {\n                return true\n            }\n        } else if neighbor != parent {\n            return true \/\/ reached an old node by a different road\n        }\n    }\n    return false\n}\n\nfunc main() {\n    tree := map[int][]int{1: {2, 3}, 2: {1}, 3: {1}}\n    loop := map[int][]int{1: {2, 3}, 2: {1, 3}, 3: {1, 2}} \/\/ triangle\n\n    \/\/ -1 means \"no parent\", because node 1 is where we start\n    fmt.Println(hasCycle(tree, 1, -1, map[int]bool{}))\n    fmt.Println(hasCycle(loop, 1, -1, map[int]bool{}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>false\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: Detect a Cycle in a Directed Graph<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Three colours for each node. iota counts up: white = 0, grey = 1, black = 2.\nconst (\n    white = iota \/\/ not visited\n    grey         \/\/ on the current DFS path\n    black        \/\/ fully done\n)\n\n\/\/ isCyclic reports whether DFS from node ever loops back onto its own path.\nfunc isCyclic(graph map[string][]string, node string, color map[string]int) bool {\n    color[node] = grey\n    for _, neighbor := range graph[node] {\n        if color[neighbor] == grey {\n            return true \/\/ neighbor is still on our path, so we looped back\n        }\n        if color[neighbor] == white &amp;&amp; isCyclic(graph, neighbor, color) {\n            return true\n        }\n    }\n    color[node] = black \/\/ every path from here is finished\n    return false\n}\n\nfunc main() {\n    safe := map[string][]string{\"api\": {\"db\", \"cache\"}, \"cache\": {\"db\"}}\n    broken := map[string][]string{\"a\": {\"b\"}, \"b\": {\"c\"}, \"c\": {\"a\"}}\n\n    fmt.Println(isCyclic(safe, \"api\", map[string]int{}))\n    fmt.Println(isCyclic(broken, \"a\", map[string]int{}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>false\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A missing key in the <code>color<\/code> map reads as 0, which is white. Grey means &#8220;on the path right now&#8221;. Reaching a black node is fine, because that branch already finished without a loop. This is how Go reports an &#8220;import cycle not allowed&#8221; error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Interview Go Graph Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go graph programs cover the questions you are most likely to meet in a coding round.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: Topological Sort (Course Schedule)<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ topoSort uses Kahn's method: repeatedly take a node with no\n\/\/ remaining prerequisites (in-degree 0).\nfunc topoSort(total int, prerequisites [][2]int) ([]int, bool) {\n    \/\/ Step 1: build the graph and count incoming edges for each node\n    nextCourses := make([][]int, total)\n    inDegree := make([]int, total)\n    for _, pair := range prerequisites { \/\/ pair[0] must come before pair[1]\n        nextCourses[pair[0]] = append(nextCourses[pair[0]], pair[1])\n        inDegree[pair[1]]++\n    }\n    \/\/ Step 2: start with every node that has no prerequisites\n    var queue, order []int\n    for i := 0; i &lt; total; i++ {\n        if inDegree[i] == 0 {\n            queue = append(queue, i)\n        }\n    }\n    \/\/ Step 3: take a ready node, then free up the nodes that depend on it\n    for len(queue) &gt; 0 {\n        course := queue[0]\n        queue = queue[1:]\n        order = append(order, course)\n        for _, next := range nextCourses[course] {\n            inDegree[next]-- \/\/ one prerequisite is now done\n            if inDegree[next] == 0 {\n                queue = append(queue, next)\n            }\n        }\n    }\n    return order, len(order) == total \/\/ if some are left, there is a cycle\n}\n\nfunc main() {\n    \/\/ 0 Go basics, 1 Functions, 2 Structs, 3 Interfaces\n    fmt.Println(topoSort(4, [][2]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}}))\n    fmt.Println(topoSort(2, [][2]int{{0, 1}, {1, 0}}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[0 1 2 3] true\n[] false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>total<\/code>. That answers &#8220;can you finish all courses?&#8221; too.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: Count Connected Components<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ visit marks node and every node it can reach.\nfunc visit(neighbors [][]int, visited []bool, node int) {\n    visited[node] = true\n    for _, next := range neighbors[node] {\n        if !visited[next] {\n            visit(neighbors, visited, next)\n        }\n    }\n}\n\n\/\/ components counts groups of nodes that can reach each other.\nfunc components(total int, edges [][2]int) int {\n    \/\/ Step 1: build the adjacency list, both directions\n    neighbors := make([][]int, total)\n    for _, edge := range edges {\n        neighbors[edge[0]] = append(neighbors[edge[0]], edge[1])\n        neighbors[edge[1]] = append(neighbors[edge[1]], edge[0])\n    }\n    \/\/ Step 2: every unvisited node starts a new group\n    visited := make([]bool, total)\n    count := 0\n    for node := 0; node &lt; total; node++ {\n        if !visited[node] {\n            count++                         \/\/ a new group starts here\n            visit(neighbors, visited, node) \/\/ mark the whole group\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(components(6, [][2]int{{0, 1}, {1, 2}, {3, 4}}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: Number of Islands<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ sink turns a land cell and all land joined to it into water.\nfunc sink(grid [][]byte, row, col int) {\n    if row &lt; 0 || col &lt; 0 || row &gt;= len(grid) || col &gt;= len(grid[0]) {\n        return \/\/ outside the grid\n    }\n    if grid[row][col] != '1' {\n        return \/\/ water or already visited\n    }\n    grid[row][col] = '0' \/\/ sink this land so we never count it again\n    sink(grid, row+1, col) \/\/ down\n    sink(grid, row-1, col) \/\/ up\n    sink(grid, row, col+1) \/\/ right\n    sink(grid, row, col-1) \/\/ left\n}\n\n\/\/ islands counts groups of '1' cells joined up, down, left or right.\nfunc islands(grid [][]byte) int {\n    count := 0\n    for row := 0; row &lt; len(grid); row++ {\n        for col := 0; col &lt; len(grid[0]); col++ {\n            if grid[row][col] == '1' {\n                count++ \/\/ found a new island\n                sink(grid, row, col)\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    \/\/ []byte(\"11000\") turns the text into a slice of characters\n    grid := [][]byte{\n        []byte(\"11000\"),\n        []byte(\"11000\"),\n        []byte(\"00100\"),\n        []byte(\"00011\"),\n    }\n    fmt.Println(islands(grid))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A grid is a graph where each cell links to its four neighbours. The loop finds a land cell, counts it, and <code>sink<\/code> wipes out the rest of that island. Changing visited land to &#8216;0&#8217; saves a separate visited set, but it changes the input, so mention that in an interview.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Rotting Oranges with Multi-Source BFS<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ cell is one position in the grid.\ntype cell struct{ row, col int }\n\n\/\/ isFresh reports whether the position is inside the grid and holds a fresh orange.\nfunc isFresh(grid [][]int, row, col int) bool {\n    if row &lt; 0 || col &lt; 0 || row &gt;= len(grid) || col &gt;= len(grid[0]) {\n        return false\n    }\n    return grid[row][col] == 1\n}\n\n\/\/ minutesToRot returns how long until every fresh orange (1) is rotten,\n\/\/ when each rotten orange (2) spreads to its neighbours every minute.\nfunc minutesToRot(grid [][]int) int {\n    \/\/ Step 1: put all rotten oranges in the queue and count the fresh ones\n    var queue []cell\n    fresh := 0\n    for row := range grid {\n        for col := range grid[row] {\n            if grid[row][col] == 2 {\n                queue = append(queue, cell{row, col})\n            } else if grid[row][col] == 1 {\n                fresh++\n            }\n        }\n    }\n    \/\/ Step 2: one round of the loop is one minute (one BFS level)\n    directions := []cell{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}\n    minutes := 0\n    for len(queue) &gt; 0 &amp;&amp; fresh &gt; 0 {\n        size := len(queue)\n        for i := 0; i &lt; size; i++ {\n            current := queue[0]\n            queue = queue[1:]\n            for _, step := range directions {\n                row := current.row + step.row\n                col := current.col + step.col\n                if isFresh(grid, row, col) {\n                    grid[row][col] = 2 \/\/ it rots now\n                    fresh--\n                    queue = append(queue, cell{row, col})\n                }\n            }\n        }\n        minutes++\n    }\n    if fresh &gt; 0 {\n        return -1 \/\/ some oranges can never be reached\n    }\n    return minutes\n}\n\nfunc main() {\n    fmt.Println(minutesToRot([][]int{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}}))\n    fmt.Println(minutesToRot([][]int{{2, 1, 1}, {0, 1, 1}, {1, 0, 1}}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>4\n-1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: Dijkstra&#8217;s Shortest Path with Weights<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ road is a one-way link to another place with a cost.\ntype road struct {\n    to   string\n    cost int\n}\n\n\/\/ item is a place and the best distance found to it so far.\ntype item struct {\n    place    string\n    distance int\n}\n\n\/\/ minHeap keeps the item with the smallest distance on top.\n\/\/ These five methods are what container\/heap needs.\ntype minHeap []item\n\nfunc (items minHeap) Len() int           { return len(items) }\nfunc (items minHeap) Less(i, j int) bool { return items[i].distance &lt; items[j].distance }\nfunc (items minHeap) Swap(i, j int)      { items[i], items[j] = items[j], items[i] } \/\/ swap two items\nfunc (items *minHeap) Push(value any)    { *items = append(*items, value.(item)) }   \/\/ .(item) gets the item back from any\nfunc (items *minHeap) Pop() any {\n    old := *items\n    last := old[len(old)-1]\n    *items = old[:len(old)-1]\n    return last\n}\n\n\/\/ dijkstra always finishes the closest unfinished place next.\nfunc dijkstra(graph map[string][]road, start string) map[string]int {\n    best := map[string]int{start: 0}\n    queue := &amp;minHeap{{start, 0}}\n    for queue.Len() &gt; 0 {\n        current := heap.Pop(queue).(item) \/\/ the closest place left\n        if current.distance &gt; best[current.place] {\n            continue \/\/ an old, longer entry: skip it\n        }\n        for _, next := range graph[current.place] {\n            newDistance := current.distance + next.cost\n            oldDistance, ok := best[next.to] \/\/ ok is true if we already have a distance\n            if !ok || newDistance &lt; oldDistance {\n                best[next.to] = newDistance \/\/ found a shorter route\n                heap.Push(queue, item{next.to, newDistance})\n            }\n        }\n    }\n    return best\n}\n\nfunc main() {\n    graph := map[string][]road{\n        \"Home\":   {{\"Market\", 4}, {\"School\", 1}},\n        \"School\": {{\"Market\", 2}, {\"Office\", 6}},\n        \"Market\": {{\"Office\", 3}},\n    }\n    distances := dijkstra(graph, \"Home\")\n    for _, place := range []string{\"Home\", \"School\", \"Market\", \"Office\"} {\n        fmt.Println(place, distances[place])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Home 0\nSchool 1\nMarket 3\nOffice 6<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">BFS vs DFS in Go Graph Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both visit every reachable node once, but they explore in different orders. The table below compares them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>BFS<\/th><th>DFS<\/th><\/tr><\/thead><tbody><tr><td>Uses<\/td><td>A queue<\/td><td>A stack or recursion<\/td><\/tr><tr><td>Order<\/td><td>Level by level<\/td><td>One branch to the end<\/td><\/tr><tr><td>Shortest path (equal costs)<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Memory<\/td><td>Can be large for wide graphs<\/td><td>Can be large for deep graphs<\/td><\/tr><tr><td>Good for<\/td><td>Shortest path, nearest item<\/td><td>Cycles, topological sort, islands<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A simple rule helps: if the question says &#8220;shortest&#8221; or &#8220;minimum steps&#8221;, use BFS. If it says &#8220;all paths&#8221;, &#8220;cycle&#8221; or &#8220;connected&#8221;, DFS is usually simpler.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Graph Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No visited set:<\/strong> the search loops forever on any cycle.<\/li>\n\n\n<li><strong>Marking visited too late in BFS:<\/strong> mark when you add to the queue, not when you remove.<\/li>\n\n\n<li><strong>Relying on map order:<\/strong> Go map order is random, so sort keys or use slices for stable output.<\/li>\n\n\n<li><strong>Treating the parent edge as a cycle:<\/strong> in undirected graphs, skip the node you came from.<\/li>\n\n\n<li><strong>Using Dijkstra with negative costs:<\/strong> use Bellman-Ford instead.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go Graph Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Number your nodes 0 to n-1<\/strong> and use slices, which are faster than maps.<\/li>\n\n\n<li><strong>Keep a parent map<\/strong> whenever you may need the actual path.<\/li>\n\n\n<li><strong>Use a heap for weighted shortest paths,<\/strong> and plain BFS for equal costs.<\/li>\n\n\n<li><strong>Check grid bounds first<\/strong> before reading a cell.<\/li>\n\n\n<li><strong>Draw the graph on paper<\/strong> and trace the queue or stack by hand.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go Graph Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Concept Questions on Go Graph Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is the time complexity of BFS and DFS?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What is the difference between a tree and a graph?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A tree is a connected graph with no cycles and exactly V &#8211; 1 edges. A general graph can have cycles, many separate parts and any number of edges.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. What is a DAG?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ in-degree: how many edges point INTO each node\n    edges := [][2]int{{0, 1}, {0, 2}, {1, 2}, {3, 2}}\n    inDegree := make([]int, 4) \/\/ four counters, all starting at 0\n    for _, edge := range edges {\n        inDegree[edge[1]]++ \/\/ edge[1] is the node the edge points to\n    }\n    fmt.Println(inDegree)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[0 1 3 0]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Node 2 has three edges pointing into it. Nodes 0 and 3 have none, so they could be done first in a topological sort.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Coding Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. How do you check if a path exists between two nodes?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ hasPath runs DFS with a stack and stops as soon as it reaches to.\nfunc hasPath(graph [][]int, from, to int) bool {\n    visited := make([]bool, len(graph))\n    stack := []int{from}\n    for len(stack) &gt; 0 {\n        node := stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n        if node == to {\n            return true\n        }\n        if visited[node] {\n            continue\n        }\n        visited[node] = true\n        stack = append(stack, graph[node]...) \/\/ ... adds every neighbour at once\n    }\n    return false\n}\n\nfunc main() {\n    graph := [][]int{{1}, {0, 2}, {1}, {4}, {3}}\n    fmt.Println(hasPath(graph, 0, 2), hasPath(graph, 0, 4))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The search starts at <code>from<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. How do you check if a graph can be coloured with two colours?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ bipartite tries to colour neighbours with opposite colours using BFS.\nfunc bipartite(graph [][]int) bool {\n    color := make([]int, len(graph)) \/\/ 0 = none, 1 and -1 are the two colours\n    for start := range graph {\n        if color[start] != 0 {\n            continue \/\/ already coloured from an earlier start\n        }\n        color[start] = 1\n        queue := []int{start}\n        for len(queue) &gt; 0 {\n            node := queue[0]\n            queue = queue[1:]\n            for _, neighbor := range graph[node] {\n                if color[neighbor] == 0 {\n                    color[neighbor] = -color[node] \/\/ give the opposite colour\n                    queue = append(queue, neighbor)\n                } else if color[neighbor] == color[node] {\n                    return false \/\/ two neighbours share a colour\n                }\n            }\n        }\n    }\n    return true\n}\n\nfunc main() {\n    square := [][]int{{1, 3}, {0, 2}, {1, 3}, {0, 2}}\n    triangle := [][]int{{1, 2}, {0, 2}, {0, 1}}\n    fmt.Println(bipartite(square), bipartite(triangle))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. How do you clone a graph?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Design Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. How would you find &#8220;people you may know&#8221; in a social app?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. Why does Go refuse import cycles?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Packages are compiled and initialised in dependency order, which needs a DAG. A cycle has no valid order, so the compiler stops with &#8220;import cycle not allowed&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. When would you use an adjacency matrix?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go graph programs, solve &#8220;word ladder&#8221;: change &#8220;cold&#8221; into &#8220;warm&#8221; one letter at a time, where every middle word must be in a list like <code>cord, card, ward, warm, worm, word<\/code>. Print the fewest steps. Hint: each word is a node, and BFS finds the shortest route.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/container\/heap\">container\/heap package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/blog\/maps\">Go maps in action on the Go blog<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/slices\">slices package documentation<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go graph programs store nodes and edges, usually as an adjacency list.<\/li>\n\n\n<li>BFS uses a queue and finds the shortest path when edges cost the same.<\/li>\n\n\n<li>DFS uses recursion or a stack and is great for cycles and islands.<\/li>\n\n\n<li>Topological sort orders tasks with dependencies and spots cycles.<\/li>\n\n\n<li>Dijkstra with a heap finds the cheapest route when edges have weights.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we put every level of this series together with the coding questions companies ask most. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-coding-interview-programs\/\">Go coding interview programs<\/a>, with LRU cache, sliding window, two pointers and dynamic programming. For more practice, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-tree-programs\/\">Go tree programs<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go graph programs model things that connect to each other, like cities joined by roads, users who follow users or tasks that depend on&hellip;<\/p>\n","protected":false},"author":1,"featured_media":855,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,123,95,11,104],"swapz_series":[],"class_list":["post-858","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-graphs","tag-go-interview-questions","tag-go-lang","tag-go-programs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Graph Programs: BFS, DFS, Topo Sort, Dijkstra<\/title>\n<meta name=\"description\" content=\"Go graph programs with output: BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra, plus graph interview Q&amp;A.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-graph-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Graph Programs: BFS, DFS, Topo Sort, Dijkstra\" \/>\n<meta property=\"og:description\" content=\"Go graph programs with output: BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra, plus graph interview Q&amp;A.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-graph-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-10T11:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"22 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Graph Programs: BFS, DFS, Topological Sort and Dijkstra\",\"datePublished\":\"2026-10-10T11:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:24+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/\"},\"wordCount\":2001,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-graph-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go Graphs\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/\",\"name\":\"Go Graph Programs: BFS, DFS, Topo Sort, Dijkstra\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-graph-programs-featured.png\",\"datePublished\":\"2026-10-10T11:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:24+00:00\",\"description\":\"Go graph programs with output: BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra, plus graph interview Q&A.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-graph-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-graph-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Graph Programs featured image: BFS, DFS and shortest path output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-graph-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Graph Programs: BFS, DFS, Topological Sort and Dijkstra\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Graph Programs: BFS, DFS, Topo Sort, Dijkstra","description":"Go graph programs with output: BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra, plus graph interview Q&A.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go Graph Programs: BFS, DFS, Topo Sort, Dijkstra","og_description":"Go graph programs with output: BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra, plus graph interview Q&A.","og_url":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-10T11:30:00+00:00","article_modified_time":"2026-11-28T19:59:24+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"22 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Graph Programs: BFS, DFS, Topological Sort and Dijkstra","datePublished":"2026-10-10T11:30:00+00:00","dateModified":"2026-11-28T19:59:24+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/"},"wordCount":2001,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-featured.png","keywords":["Beginner","Go Graphs","Go Interview Questions","Go Lang","Go Programs"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/","name":"Go Graph Programs: BFS, DFS, Topo Sort, Dijkstra","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-featured.png","datePublished":"2026-10-10T11:30:00+00:00","dateModified":"2026-11-28T19:59:24+00:00","description":"Go graph programs with output: BFS, DFS, shortest path, cycle checks, topological sort, number of islands and Dijkstra, plus graph interview Q&A.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-graph-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-graph-programs-featured.png","width":2400,"height":1260,"caption":"Go Graph Programs featured image: BFS, DFS and shortest path output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-graph-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Graph Programs: BFS, DFS, Topological Sort and Dijkstra"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/858","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=858"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/858\/revisions"}],"predecessor-version":[{"id":903,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/858\/revisions\/903"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/855"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=858"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=858"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=858"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=858"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}