fn get_score(const x y : int, a : array(byte, [x, y]), i j : int) : int [ var score := 0; var set := treemap_init(tuple3(byte, int, int), int); var t := mktuple3(a[i, j], i, j); set := treemap_insert(set, t, 1); while true do [ var first := treemap_first(set); if first is n then break; var k := first.j.k; var v := first.j.v; set := treemap_delete(set, k); if k.v1 = '9' then [ score += v; continue; ] for d in [ [0, 1], [0, -1], [1, 0], [-1, 0] ] do [ var xp := k.v2 + d[0]; var yp := k.v3 + d[1]; if xp >= 0, xp < x, yp >= 0, yp < y, a[xp, yp] = k.v1 + 1 then [ var t := mktuple3(a[xp, yp], xp, yp); var ex := treemap_search(set, t); var paths := select(ex is j, 0, ex.j); set := treemap_insert(set, t, paths + v); ] ] ] return score; ] fn main [ var lines := list_break_to_lines(read_lazy(h[0])); lines := list_flatten(lines); const x := len(lines[0]); const y := len(lines); var a := list_to_array([x, y], list_join(lines, "")); a := array_flatten(a); var score := 0; for i := 0 to x do [ for j := 0 to y do [ if a[i, j] = '0' then score += get_score(a, i, j); ] ] write(h[1], ntos(score) + nl); ]