#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
ll a[1000][1000], Q, n;
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    //Author: PhuocThien.
    // Input
    cin >> n;
    for(ll i = 1; i <= n; i ++)
        for(ll j = 1; j <= n; j ++)
            cin >> a[i][j];
    cin >> Q;
    while(Q --) {
        string s;
        cin >> s;
        ll x, y;
        cin >> x >> y;
        bool ok = true;
        // TEST
        ll ans = a[x][y];
        // update 1
        for(ll i = 0; i < (ll)s.size(); i ++) {
            if(s[i] == 'L') y --;
            // LEFT
            if(s[i] == 'R') y ++;
            //RIGHT
            if(s[i] == 'U') x --;
            //UP
            if(s[i] == 'D') x ++;
            //DOWN
            ans += a[x][y];
            // update
            if(a[x][y] == 0) {
                // ERROR
                cout << "-1\n";
                ok = false;
                break;
            }
        }
        if(ok) cout << ans << endl;
    }
}
