#include <bits/stdc++.h>
#define i64 long long
#define u64 unsigned long long
#define i32 int
#define u32 unsigned int
#define pii pair<int, int>
#define pll pair<long long, long long>
#define F first
#define S second
#define ld long double
#define defmod 1000000007
#define mati64(a,b) vector<vector<i64>>(a, vector<i64>(b, 0));
using namespace std;
int fuckme[4][2];
int main(){
cin.sync_with_stdio(0);
cin.tie(0);
int tr[1000];
fuckme[0][0] = -1;
fuckme[1][1] = 1;
fuckme[2][0] = 1;
fuckme[3][1] = -1;
tr['U'] = 0;
tr['R'] = 1;
tr['D'] = 2;
tr['L'] = 3;
int n, m, k; cin >> n >> m >> k;
int x, y; cin >> x >> y;
x--;
y--;
int bi[10], bj[10], bd[10];
string t[5][55];
for(int ba = 0; ba < k; ++ba){
char fak; cin >> bi[ba] >> bj[ba] >> fak;
bi[ba]--;
bj[ba]--;
bd[ba] = tr[fak];
for(int i = 0; i < n; ++i)
cin >> t[ba][i];
}
pair<pii, pii> ne[5][55][55][4];
for(int ba = 0; ba < k; ++ba){
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
for(int di = 0; di < 4; ++di){
int ndi = (di+t[ba][i][j]-'0')%4;
if(i == 0 && ndi == 0)
ndi = 2;
else if(j == 0 && ndi == 3)
ndi = 1;
else if(i == n-1 && ndi == 2)
ndi = 0;
else if(j == m-1 && ndi == 1)
ndi = 3;
pii mv = {i+fuckme[ndi][0], j+fuckme[ndi][1]};
ne[ba][i][j][di] = {mv, {ndi, 0}};
}
}
}
}
vector<int> myy(10, -1), lam(10, -1);
vector<i64> es[10], ss[10];
for(int ba = 0; ba < k; ++ba){
queue<pair<pii, pii>> q;
q.push({{bi[ba], bj[ba]}, {bd[ba], 0}});
bool d1[55][55][4] = {0};
int dis[55][55][4] = {0};
while(!q.empty()){
int i = q.front().F.F, j = q.front().F.S, di = q.front().S.F, d = q.front().S.S;
q.pop();
//cout << "taalla " << i << "," << j << " " << di << " " << d << endl;
if(d1[i][j][di]){
while(es[ba].size() > 0 && es[ba].back() >= dis[i][j][di]){
ss[ba].push_back(es[ba].back());
es[ba].pop_back();
}
lam[ba] = d-dis[i][j][di];
break;
}
d1[i][j][di] = 1;
dis[i][j][di] = d;
if(i == x && j == y)
es[ba].push_back(d);
pair<pii, pii> lul = ne[ba][i][j][di];
lul.S.S = d+1;
q.push(lul);
}
/*
cout << "bakteeri " << ba << " : ";
for(auto f: es[ba])
cout << f << " ";
cout << "syklin koko " << lam[ba] << " ";
cout << "syklissa ";
for(auto f: ss[ba])
cout << f<< " ";
cout << endl;
*/
}
i64 ans = 1LL<<60;
for(int ba = 0; ba < k; ++ba){
for(auto f: es[ba]){
bool ok = true;
for(int ba2 = 0; ba2 < k; ++ba2){
if(ba2 == ba)
continue;
bool ok2 = false;
for(auto ff: es[ba2]){
if(ff == f)
ok2 = true;
}
for(auto ff: ss[ba2]){
if(f-ff >= 0 && (f-ff)%lam[ba2] == 0)
ok2 = true;
}
ok&=ok2;
}
if(ok)
ans = min(ans, f);
}
}
for(auto fff: ss[0]){
for(int i = 0; i < 1000000; ++i){
i64 f = fff+i*lam[0];
//cout << "taalla " << f << endl;
bool ok = true;
for(int ba2 = 1; ba2 < k; ++ba2){
bool ok2 = false;
for(auto ff: es[ba2]){
if(ff == f)
ok2 = true;
}
for(auto ff: ss[ba2]){
if(f-ff >= 0 && (f-ff)%lam[ba2] == 0)
ok2 = true;
}
ok&=ok2;
}
if(ok)
ans = min(ans, f);
}
}
if(ans == 1LL<<60)
cout << -1 << endl;
else
cout << ans+1 << endl;
return 0;
}