#include <iostream> #include <vector> #include <algorithm> const long mod = 100007; using namespace std; vector<vector<long long>> mem; long long cnt = 0; long long mem_track(vector<vector<int>>& a,vector<vector<int>>& b,int endx,int endy,vector<vector<bool>>& vis){ if(vis[endx][endy]) return mem[endx][endy]; vis[endx][endy] = true; mem[endx][endy] = 1; if(endx - 1 >= 0 && a[endx-1][endy] + b[endx-1][endy] <= a[endx][endy]) {mem[endx][endy] += mem_track(a,b,endx-1,endy,vis); mem[endx][endy] %= mod;} if(endx + 1 < a.size() && a[endx+1][endy] + b[endx+1][endy] <= a[endx][endy]) {mem[endx][endy] += mem_track(a,b,endx+1,endy,vis); mem[endx][endy] %= mod;} if(endy - 1 >= 0 && a[endx][endy-1] + b[endx][endy-1] <= a[endx][endy]) {mem[endx][endy] += mem_track(a,b,endx,endy-1,vis); mem[endx][endy] %= mod;} if(endy + 1 < a[0].size() && a[endx][endy+1] + b[endx][endy+1] <= a[endx][endy]) {mem[endx][endy] += mem_track(a,b,endx,endy+1,vis); mem[endx][endy] %= mod;} return mem[endx][endy]; } int main(){ int n = 0, m = 0; cin >> n >> m; vector<vector<int>> a(n,vector<int>(m)); vector<vector<int>> b(n,vector<int>(m)); mem.resize(n,vector<long long>(m)); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> a[i][j]; } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> b[i][j]; } } int q = 0; cin >> q; vector<vector<bool>> vis(n,vector<bool>(m,false)); while(q--){ int x ,y; cin >> x >> y; cout << mem_track(a,b,x-1,y-1,vis) << endl; } return 0; }