D=[[{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}],[{-1,-1},{-1,1},{1,-1},{1,1}]] h,w=gets.not_nil!.split.map(&.to_i) g=q=[] of Tuple(Int32,Int32,Int32) m=[] of String h.times{|y|s=gets.not_nil!.chomp;s.size.times{|x|s[x]=='S'&&q<<{0,x,y};s[x]=='G'&&(g=[{x,y,1}])};m<0} while !q.empty? c,cx,cy=q.shift D[c].each{|(dx,dy)| nx,ny=cx+dx,cy+dy if 0<=nx&&nx