@w=pop=~/./g;($g,$a,$b)=@_;@s=(0,[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]);sub t{my($D,$N,@C)=@_;@C=map{$C[$_]+$s[$D][$_]}(0,1);if(!($C[0]+1)||$C[0]==$a){0}elsif(!($C[1]+1)||$C[1]==$b){0}elsif($w[$N]ne$g->[$C[0]][$C[1]]){0}elsif($N==$#w){1}else{t($D,$N+1,@C)}}for$x(0..$a-1){for$y(0..$b-1){next if($g->[$x][$y]ne$w[0]);for$d(1..8){return($x,$y,$d)if t($d,1,$x,$y)}}}undef