#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <numeric>
#include <cctype>
#include <tuple>
#include <array>
#include <climits>

// BEGIN CUT HERE
#ifdef _MSC_VER
#include <agents.h>
#endif
// END CUT HERE 

#define FOR(i, a, b) for(int i = (a); i < (int)(b); ++i)
#define rep(i, n) FOR(i, 0, n)
#define ALL(v) v.begin(), v.end()
#define REV(v) v.rbegin(), v.rend()
#define MEMSET(v, s) memset(v, s, sizeof(v))
#define MP make_pair
#define MT make_tuple

using namespace std;

typedef pair<int, int> P;
typedef long long ll;

const int N = 1e5 + 10;

vector<int> G[N];

struct state{
	int r, c, t, d;
	bool operator < (const state &rhs) const{
		return d > rhs.d;
	}
};

int dist[25][25][210];

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

inline int &getdist(state &s){
	return dist[s.r][s.c][s.t];
}

void go(state nxt, priority_queue<state> &q){
	int &d = getdist(nxt);
	if (d <= nxt.d) return;
	d = nxt.d;
	q.push(nxt);
}

int a[210];

int main(){
	int h, w;
	cin >> h >> w;
	vector<string> tmp(h);
	rep(i, h) cin >> tmp[i];
	int n;
	cin >> n;
	vector<vector<string>> area(n+1, vector<string>(h));
	area[0] = tmp;

	MEMSET(a, -1);
	a[0] = 0;
	FOR(i, 1, n + 1){
		int x;
		cin >> x;
		a[x] = i;
		rep(j, h) cin >> area[i][j];
	}
	rep(i, 200) if (a[i + 1] < 0) a[i + 1] = a[i];

	rep(i, 25) rep(j, 25) rep(k, 210) dist[i][j][k] = 1e9;

	P start, goal;
	rep(i, h) rep(j, w){
		if (tmp[i][j] == 'S') start = MP(i, j);
		if (tmp[i][j] == 'G') goal = MP(i, j);
	}

	priority_queue<state> q;
	go({ start.first, start.second, 0, 0 }, q);
	while (!q.empty()){
		auto s = q.top();
		q.pop();

		if (getdist(s) < s.d) continue;

		if (s.r == goal.first && s.c == goal.second){
			cout << s.d << endl;
			return 0;
		}

		s.t = min(s.t+1, 200);
		++s.d;
		rep(d, 5){
			state nxt = s;
			if (d == 4) --nxt.d;
			nxt.r += dx[d], nxt.c += dy[d];
			if (nxt.r < 0 || nxt.r >= h || nxt.c < 0 || nxt.c >= w) continue;
			int na = a[nxt.t];
			if (area[na][nxt.r][nxt.c] == '#') continue;
			go(nxt, q);
		}
	}
	cout << -1 << endl;

	return 0;
}
