Approach
Breadth-first search
For Codeforces 590C — Three States, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 97 lines of Go from the credited upstream file 590C.go.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7)8 910type pair90 struct{ x, y int }11type deque90 struct{ l, r []pair90 }12 13func (q deque90) empty() bool { return len(q.l) == 0 && len(q.r) == 0 }14func (q *deque90) pushL(v pair90) { q.l = append(q.l, v) }15func (q *deque90) pushR(v pair90) { q.r = append(q.r, v) }16func (q *deque90) popL() (v pair90) {17 if len(q.l) > 0 {18 q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1]19 } else {20 v, q.r = q.r[0], q.r[1:]21 }22 return23}24 25func CF590C(_r io.Reader, out io.Writer) {26 in := bufio.NewReader(_r)27 dir4 := []pair90{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}28 29 var n, m int30 Fscan(in, &n, &m)31 g := make([][]byte, n)32 for i := range g {33 Fscan(in, &g[i])34 }35 bfs := func(tp byte) [][]int {36 dis := make([][]int, n)37 for i := range dis {38 dis[i] = make([]int, m)39 for j := range dis[i] {40 dis[i][j] = 1e841 }42 }43 q := &deque90{}44 for i, r := range g {45 for j, b := range r {46 if b == tp {47 dis[i][j] = 048 q.pushL(pair90{i, j})49 }50 }51 }52 for !q.empty() {53 p := q.popL()54 for _, d := range dir4 {55 if x, y := p.x+d.x, p.y+d.y; 0 <= x && x < n && 0 <= y && y < m && g[x][y] != '#' {56 d := 057 if g[x][y] == '.' {58 d = 159 }60 if newD := dis[p.x][p.y] + d; newD < dis[x][y] {61 dis[x][y] = newD62 if d == 0 {63 q.pushL(pair90{x, y})64 } else {65 q.pushR(pair90{x, y})66 }67 }68 }69 }70 }71 return dis72 }73 d1 := bfs('1')74 d2 := bfs('2')75 d3 := bfs('3')76 ans := int(1e7)77 for i, r := range g {78 for j, b := range r {79 if b != '#' {80 d := d1[i][j] + d2[i][j] + d3[i][j]81 if b == '.' {82 d -= 283 }84 if d < ans {85 ans = d86 }87 }88 }89 }90 if ans == 1e7 {91 ans = -192 }93 Fprint(out, ans)94}95 9697