def hinan_keiro(H, W, gy, gx, org_grid, queries): H = H + 2 W = W + 2 goal = (gy * W) + gx result = [] for query in queries: sy, sx, k = query start = (sy * W) + sx k = k**2 # initialize calc grid calc_grid = [0]*W for row in org_grid: calc_grid += [0] + list(map(lambda val: val + k, row)) + [0] calc_grid += [0]*W # initialize count count = calc_grid[start] - 1 calc_grid[start] = 1 # initialize decrease points dec_points = tuple([start]) while calc_grid[goal] != 0: # debug ----- # for r in range(0, H): # print(calc_grid[r * W:r * W + W]) # input() # ----- # copy decrease points to buffer buffer = set(dec_points) for point in dec_points: calc_grid[point] -= 1 if calc_grid[point] == 0: buffer.remove(point) for new_point in [point - 1, point + 1, point - W, point + W]: if calc_grid[new_point] > 0: buffer.add(new_point) dec_points = tuple(buffer) count += 1 result.append(count) return result if __name__ == '__main__': H, W = map(int, input().split(' ')) gy, gx = map(int, input().split(' ')) grid = tuple([ tuple(map(int, input().split(' '))) for i in range(H)]) Q = int(input()) queries = tuple([ tuple(map(int, input().split(' '))) for i in range(Q)]) # import time # start_time = time.time() result = hinan_keiro(H, W, gy, gx, grid, queries) for i in result: print(i) # process_time = time.time() - start_time # print('process_time = ' + str(process_time))