import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int h = sc.nextInt(); int w = sc.nextInt(); PriorityQueue queue = new PriorityQueue<>(); queue.add(new Path((sc.nextInt() - 1) * w + sc.nextInt() - 1, 1, 0)); int[] field = new int[h * w]; ArrayList> costs = new ArrayList<>(); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { field[i * w + j] = sc.nextInt(); costs.add(new TreeMap<>()); } } while (queue.size() > 0) { Path p = queue.poll(); if (costs.get(p.idx).size() > 0 && costs.get(p.idx).lastEntry().getValue() <= p.value) { continue; } costs.get(p.idx).put(p.count, p.value); if (p.idx % w > 0) { queue.add(new Path(p.idx - 1, p.count + 1, p.value + field[p.idx])); } if (p.idx % w < w - 1) { queue.add(new Path(p.idx + 1, p.count + 1, p.value + field[p.idx])); } if (p.idx / w > 0) { queue.add(new Path(p.idx - w, p.count + 1, p.value + field[p.idx])); } if (p.idx / w < h - 1) { queue.add(new Path(p.idx + w, p.count + 1, p.value + field[p.idx])); } } StringBuilder sb = new StringBuilder(); int q = sc.nextInt(); for (int i = 0; i < q; i++) { int idx = (sc.nextInt() - 1) * w + sc.nextInt() - 1; long k = sc.nextInt(); k *= k; long ans = Long.MAX_VALUE; for (Map.Entry entry : costs.get(idx).entrySet()) { int key = entry.getKey(); int value = entry.getValue(); ans = Math.min(ans, k * key + value + field[idx]); } sb.append(ans).append("\n"); } System.out.print(sb); } static class Path implements Comparable { int idx; int count; int value; public Path(int idx, int count, int value) { this.idx = idx; this.count = count; this.value = value; } public int compareTo(Path another) { if (count == another.count) { return value - another.value; } else { return count - another.count; } } } }