def getstart(s): for i in range(len(s)): for j in range(len(s[i])): if s[i][j] == 'S': return (i, j, 0, 0) def knight(w,h,i,j): for a in [-1, +1]: for b in [-2, +2]: na = i+a nb = j+b if (0 <= na < h) and (0 <= nb < w): yield (na, nb) for a in [-2, +2]: for b in [-1, +1]: na = i+a nb = j+b if (0 <= na < h) and (0 <= nb < w): yield (na, nb) def bishop(w,h,i,j): for a in [-1, +1]: for b in [-1, +1]: na = i+a nb = j+b if (0 <= na < h) and (0 <= nb < w): yield (na, nb) def main(): h,w = map(int, input().split()) s = [input() for i in range(h)] q = [getstart(s)] visited = set() while q: i,j,bn,d = q.pop(0) visited.add((i,j)) if s[i][j] == 'G': print(d) return elif s[i][j] == 'R': bn += 1 if bn % 2 == 0: for ni,nj in knight(w, h, i, j): if (ni,nj) not in visited: q.append((ni,nj,bn,d+1)) else: for ni,nj in bishop(w, h, i, j): if (ni,nj) not in visited: q.append((ni,nj,bn,d+1)) print(-1) if __name__ == '__main__': main()