#include <iostream>
#include <vector>

using namespace std;

class range {
private:
  struct Iterator {
    int val;
    int operator*() {return val;}
    bool operator!=(Iterator &itr) {return val < itr.val;}
    void operator++() {++val;}
  };
  Iterator i, n;
public:
  range(int n) : i({0}), n({n}) {}
  range(int i, int n) : i({i}), n({n}) {}
  Iterator &begin() {return i;}
  Iterator &end() {return n;}
};

template<class T> T at(vector<T> v, int i) {return v[(i % (int)v.size() + v.size()) % v.size()];}

const int INF = 1e9;

const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, -1, 0, 1};

int main() {
  int h, w;
  cin >> h >> w;
  string area[16][h];
  for (int i : range(h)) cin >> area[0][i];
  int n;
  cin >> n;
  int t[n];
  for (int i : range(n)) {
    cin >> t[i];
    for (int j : range(h)) cin >> area[i + 1][j];
  }
  int dp[1000][h][w];
  for (int i : range(1000)) for (int j : range(h)) for (int k : range(w)) dp[i][j][k] = INF;
  for (int i : range(h)) for (int j : range(w)) if (area[0][i][j] == 'S') dp[0][i][j] = 0;
  int s = 0, res = INF;
  for (int i : range(999)) {
    if (s < n && t[s] == i + 1) ++s;
    for (int y : range(h)) for (int x : range(w)) if (dp[i][y][x] != INF) {
      for (int k : range(4)) {
        int yy = y + dy[k];
        int xx = x + dx[k];
        if (yy < 0 || h <= yy) continue;
        if (xx < 0 || w <= xx) continue;
        if (area[s][yy][xx] == '#') continue;
        dp[i + 1][yy][xx] = min(dp[i + 1][yy][xx], dp[i][y][x] + 1);
        if (area[0][yy][xx] == 'G') res = min(res, dp[i][y][x] + 1);
      }
      if (area[s][y][x] != '#') dp[i + 1][y][x] = min(dp[i + 1][y][x], dp[i][y][x]);
    }
  }
  if (res == INF) cout << -1 << endl;
  else cout << res << endl;
}
