from sys import stdin class UnionFind: def __init__(self,n): self.n = n self.parent_size = [-1]*n def leader(self,a): if self.parent_size[a] < 0: return a self.parent_size[a] = self.leader(self.parent_size[a]) return self.parent_size[a] def merge(self,a,b): x, y = self.leader(a), self.leader(b) if x == y: return if abs(self.parent_size[x]) < abs(self.parent_size[y]): x, y = y, x self.parent_size[x] += self.parent_size[y] self.parent_size[y] = x return def same(self,a,b): return self.leader(a) == self.leader(b) def size(self,a): return abs(self.parent_size[self.leader(a)]) def groups(self): result = [[] for _ in range(self.n)] for i in range(self.n): result[self.leader(i)].append(i) return [r for r in result if r != []] H, W = map(int, input().split()) A = [list(map(int, stdin.readline().split())) for _ in range(H)] Q = int(input()) query = [list(map(int, stdin.readline().split())) for _ in range(Q)] def IDX(i, j): return i*W+j edge = [] for i in range(H): for j in range(W): if i+1 < H: edge.append((IDX(i, j), IDX(i+1, j), max(A[i][j], A[i+1][j]))) if j+1 < W: edge.append((IDX(i, j), IDX(i, j+1), max(A[i][j:j+2]))) edge.sort(key=lambda x:x[2]) left = [0]*Q right = [len(edge)]*Q mid = [[] for _ in range(len(edge)+1)] for i in range(Q): mid[len(edge)//2].append(i) cnt = 0 while cnt < Q: UF = UnionFind(H*W) for i in range(len(edge)+1): while mid[i]: idx = mid[i].pop() sh, sw, gh, gw = query[idx] if UF.same(IDX(sh-1, sw-1), IDX(gh-1, gw-1)): right[idx] = i else: left[idx] = i if left[idx]+1 == right[idx]: cnt += 1 else: mid[(left[idx]+right[idx])//2].append(idx) if i < len(edge): v, w, c = edge[i] UF.merge(v, w) for i in range(Q): print(edge[left[i]][2])