#!/usr/bin/env tclsh9.0 namespace import ::tcl::mathop::+ namespace import ::tcl::mathop::- 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 search {grid rows cols} { set count 0 # Look at each 3x3 subgrid. for {set r 0} {$r < $rows - 2} {incr r} { for {set c 0} {$c < $cols - 2} {incr c} { if {[lindex $grid [+ $r 1] [+ $c 1]] ne "A"} continue # With the center confirmed, we need both diagonals to match. # Each diagonal has two possible forms (M+S or S+M). # Down-Right set word "[lindex $grid $r $c][lindex $grid [+ $r 2] [+ $c 2]]" if {$word ne "MS" && $word ne "SM"} continue # Down-Left set word "[lindex $grid $r [+ $c 2]][lindex $grid [+ $r 2] $c]" if {$word ne "MS" && $word ne "SM"} continue incr count } } return $count } puts [search $grid $rows $cols]