#!/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} { array unset seen foreach e [endpoints $r $c] { set seen($e) 1 } # puts "r=$r c=$c ends=[array size seen] seen=[array get seen]" incr total [array size seen] } } } puts $total } proc endpoints {r c} { global grid rows cols set here [lindex $grid $r $c] if {$here == 9} {return [list [list $r $c]]} set ends [list] if {$r > 0 && [lindex $grid $r-1 $c] == [+ $here 1]} { lappend ends {*}[endpoints [- $r 1] $c] } if {$r < [- $rows 1] && [lindex $grid $r+1 $c] == [+ $here 1]} { lappend ends {*}[endpoints [+ $r 1] $c] } if {$c > 0 && [lindex $grid $r $c-1] == [+ $here 1]} { lappend ends {*}[endpoints $r [- $c 1]] } if {$c < [- $cols 1] && [lindex $grid $r $c+1] == [+ $here 1]} { lappend ends {*}[endpoints $r [+ $c 1]] } return $ends } input count