class Integer def mod_inverse(mod) self.pow(mod - 2, mod) end end H, W = gets.split.map(&:to_i) A = H.times.map { gets.split.map(&:to_i) } MOD = 10 ** 9 + 7 R = [] all = 1 H.times do |i| W.times do |j| all *= A[i][j] all %= MOD end end H.times do |i| row = 1 W.times do |j| row *= A[i][j] row %= MOD end R << row end C = [] W.times do |j| col = 1 H.times do |i| col *= A[i][j] col %= MOD end C << col end Q = gets.to_i Q.times do r, c = gets.split.map(&:to_i) ans = (all * R[r - 1].mod_inverse(MOD) * C[c - 1].mod_inverse(MOD) * A[r - 1][c - 1]) % MOD puts ans end