Approach
Breadth-first search
For Codeforces 677D — Vanya and Treasure, 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
- 49 lines of Go from the credited upstream file 677D.go.
- The implementation visibly relies on sequence storage.
- 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 "sort"8)9 1011func CF677D(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 abs := func(x int) int {14 if x < 0 {15 return -x16 }17 return x18 }19 type pair struct{ x, y, d int }20 21 var n, m, p, v int22 Fscan(in, &n, &m, &p)23 pos := make([][]pair, n*m+1)24 pos[0] = []pair{{}}25 for i := 0; i < n; i++ {26 for j := 0; j < m; j++ {27 Fscan(in, &v)28 pos[v] = append(pos[v], pair{i, j, 1e9})29 }30 }31 for i, ps := range pos[:p] {32 sort.Slice(ps, func(i, j int) bool { return ps[i].d < ps[j].d })33 if len(ps) > n+m {34 35 ps = ps[:n+m]36 }37 for _, p := range ps {38 for k, q := range pos[i+1] {39 if d := p.d + abs(p.x-q.x) + abs(p.y-q.y); d < q.d {40 pos[i+1][k].d = d41 }42 }43 }44 }45 Fprint(out, pos[p][0].d)46}47 4849