#!/usr/bin/env tclsh8.6 set row 0 while {[gets stdin line] >= 0} { set col 0 foreach c [split $line {}] { set grid($row,$col) $c incr col } incr row } # set steps 100 # if {[llength $argv]} {set steps [lindex $argv 0]} proc energize {r c} { global grid row col if {$r < 0 || $c < 0} return if {$r >= $row || $c >= $col} return incr grid($r,$c) if {$grid($r,$c) == 10} { foreach dr {-1 0 1} { foreach dc {-1 0 1} { if {$dr == 0 && $dc == 0} continue energize [expr {$r + $dr}] [expr {$c + $dc}] } } } } set step 0 while 1 { incr step set flash 0 for {set r 0} {$r < $row} {incr r} { for {set c 0} {$c < $col} {incr c} { energize $r $c } } for {set r 0} {$r < $row} {incr r} { for {set c 0} {$c < $col} {incr c} { if {$grid($r,$c) > 9} { set grid($r,$c) 0 incr flash } } } if {$flash == $row * $col} {puts $step; break} }