Skip to content

Commit

Permalink
2022_12: golang solution(part 2)
Browse files Browse the repository at this point in the history
  • Loading branch information
MellKam committed Dec 25, 2022
1 parent 87f1c05 commit c407059
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 43 deletions.
33 changes: 33 additions & 0 deletions 2022/day_12/golang/graph/bfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,39 @@ func GetShortestPath(startVertex *Vertex, endCoords Coords) int {
}

key = neighbour.Key()
if !visited[key] {
queue = append(queue, BFSNode{vertex: neighbour, distance: node.distance + 1})
visited[key] = true
}
}
}

return -1
}

func FindShortestPathToValue(startVertex *Vertex, targetValue byte) int {
visited := make(map[Coords]bool)
queue := make([]BFSNode, 0)

queue = append(queue, BFSNode{vertex: startVertex, distance: 0})
visited[startVertex.Key()] = true

for len(queue) > 0 {
node := queue[0]
queue = queue[1:]

if node.vertex.value == targetValue {
return node.distance
}

nextNeighbour := node.vertex.Iter()
for {
neighbour := nextNeighbour()
if neighbour == nil {
break
}

key := neighbour.Key()

if !visited[key] {
queue = append(queue, BFSNode{vertex: neighbour, distance: node.distance + 1})
Expand Down
13 changes: 11 additions & 2 deletions 2022/day_12/golang/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ func main() {
panic("startVertex is nil")
}

shortestPath := graph.GetShortestPath(startVertex, endCoords)
endVertex := g.GetVertex(endCoords)
if endVertex == nil {
panic("endVertex is nil")
}

shortestPath := graph.FindShortestPathToValue(endVertex, byte('a')-96)

fmt.Println(shortestPath)
}
Expand Down Expand Up @@ -92,7 +97,11 @@ func ConnectVertexesByTarget(v1 *graph.Vertex, v2 *graph.Vertex) {
return
}

if int(v2.Value())-int(v1.Value()) <= 1 {
delta := int(v2.Value()) - int(v1.Value())

// for part one with going up -> (v <= 1)
// for part two with going down -> (v >= -1)
if delta >= -1 {
v1.AddEdge(v2)
}
}
41 changes: 0 additions & 41 deletions 2022/day_12/map.txt

This file was deleted.

0 comments on commit c407059

Please sign in to comment.