- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 75 lines of Go from the credited upstream file 173B.go.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 9type dPair173 struct{ x, y, dir int }10type deque173 struct{ l, r []dPair173 }11 12func (q *deque173) empty() bool { return len(q.l) == 0 && len(q.r) == 0 }13func (q *deque173) pushL(v dPair173) { q.l = append(q.l, v) }14func (q *deque173) pushR(v dPair173) { q.r = append(q.r, v) }15func (q *deque173) popL() (v dPair173) {16 if len(q.l) > 0 {17 q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1]18 } else {19 v, q.r = q.r[0], q.r[1:]20 }21 return22}23 2425func CF173B(_r io.Reader, _w io.Writer) {26 in := bufio.NewReader(_r)27 out := bufio.NewWriter(_w)28 defer out.Flush()29 30 dir4 := [...][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}31 var n, m int32 Fscan(in, &n, &m)33 mat := make([][]byte, n)34 for i := range mat {35 Fscan(in, &mat[i])36 }37 const mx, inf = 1000, 1e938 dist := [mx][mx][4]int{}39 for i, di := range dist {40 for j, dij := range di {41 for k := range dij {42 dist[i][j][k] = inf43 }44 }45 }46 dist[n-1][m-1][3] = 047 q := &deque173{}48 q.pushL(dPair173{n - 1, m - 1, 3})49 for !q.empty() {50 p := q.popL()51 x, y, dir := p.x, p.y, p.dir52 d := dist[x][y][dir]53 if xx, yy := x+dir4[dir][0], y+dir4[dir][1]; xx >= 0 && xx < n && yy >= 0 && yy < m && d < dist[xx][yy][dir] {54 dist[xx][yy][dir] = d55 q.pushL(dPair173{xx, yy, dir})56 }57 if mat[x][y] == '#' {58 for i := 0; i < 4; i++ {59 if i != dir && d+1 < dist[x][y][i] {60 dist[x][y][i] = d + 161 q.pushR(dPair173{x, y, i})62 }63 }64 }65 }66 if dist[0][0][3] == inf {67 dist[0][0][3] = -168 }69 Fprint(out, dist[0][0][3])70}71 72737475