egonSchiele / grokking_algorithms

Code for the book Grokking Algorithms (https://amzn.to/29rVyHf)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dijkstra Algorithm Golang Issue

BrianMwangi21 opened this issue · comments

Hi guys, I am trying to run the Golang implementation on the graph below and the cost to the stop is the MaxInt set in the beginning.

	graph["start"] = map[string]int{}
	graph["start"]["b"] = 5
	graph["start"]["c"] = 2

	graph["b"] = map[string]int{}
	graph["b"]["d"] = 1
	graph["b"]["e"] = 4

	graph["c"] = map[string]int{}
	graph["c"]["b"] = 8
	graph["c"]["d"] = 7

	graph["d"] = map[string]int{}
	graph["d"]["stop"] = 1

	graph["e"] = map[string]int{}
	graph["e"]["d"] = 6
	graph["e"]["stop"] = 3
	
	graph["stop"] = map[string]int{}

I have added the following lines in the implementation while looping through the nodes of the lowestCostNode and it seems to now be working but I am not certain if that's the best approach or otherwise.

		for lowestCostNode != "" {
		for node, cost := range graph[lowestCostNode] {
			// The following three lines have been added
			if _, isSet := costs[node]; !isSet {
				costs[node] = cost
			}
			
			newCost := costs[lowestCostNode] + cost

			if newCost < costs[node] {
				costs[node] = newCost
				parents[node] = lowestCostNode
			}
		}

		processed[lowestCostNode] = true
		lowestCostNode = findLowestCostNode(costs, processed)
	}

You can find my full implementation here together with the tests : https://github.com/BrianMwangi21/grokking-algos/tree/main/dijkstra