#!/usr/bin/env tclsh9.0 namespace import ::tcl::mathop::+ namespace import ::tcl::mathop::- proc input {} { global grid rows cols set rows 0 set grid [list] while {[gets stdin line] >= 0} { if {$line eq ""} continue incr rows set cols [string length $line] lappend grid [split $line ""] } } proc count {} { global grid rows cols set total 0 for {set r 0} {$r < $rows} {incr r} { for {set c 0} {$c < $cols} {incr c} { if {[lindex $grid $r $c] == 0} { incr total [score $r $c] } } } puts $total } proc score {r c} { global grid rows cols set here [lindex $grid $r $c] if {$here == 9} {return 1} set n 0 if {$r > 0 && [lindex $grid $r-1 $c] == [+ $here 1]} { incr n [score [- $r 1] $c] } if {$r < [- $rows 1] && [lindex $grid $r+1 $c] == [+ $here 1]} { incr n [score [+ $r 1] $c] } if {$c > 0 && [lindex $grid $r $c-1] == [+ $here 1]} { incr n [score $r [- $c 1]] } if {$c < [- $cols 1] && [lindex $grid $r $c+1] == [+ $here 1]} { incr n [score $r [+ $c 1]] } return $n } input count