Please notice the unusual memory limit of this problem.

Orac likes games. Recently he came up with the new game, "Game of Life".

You should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white.

For each iteration of the game (the initial iteration is $0$), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different.

Two cells are adjacent if they have a mutual edge.

Now Orac has set an initial situation, and he wants to know for the cell $(i,j)$ (in $i$-th row and $j$-th column), what will be its color at the iteration $p$. He may ask you these questions several times. 


-----Input-----

The first line contains three integers $n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$, representing the number of rows, columns, and the number of Orac queries.

Each of the following $n$ lines contains a binary string of length $m$, the $j$-th character in $i$-th line represents the initial color of cell $(i,j)$. '0' stands for white, '1' stands for black.

Each of the following $t$ lines contains three integers $i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$, representing a query from Orac.


-----Output-----

Print $t$ lines, in $i$-th line you should print the answer to the $i$-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'.


-----Examples-----
Input
3 3 3
000
111
000
1 1 1
2 2 2
3 3 3

Output
1
1
1

Input
5 2 2
01
10
01
10
01
1 1 4
5 1 4

Output
0
0

Input
5 5 3
01011
10110
01101
11010
10101
1 1 4
1 2 3
5 5 3

Output
1
0
1

Input
1 1 3
0
1 1 1
1 1 2
1 1 3

Output
0
0
0



-----Note----- [Image] 

For the first example, the picture above shows the initial situation and the color of cells at the iteration $1$, $2$, and $3$. We can see that the color of $(1,1)$ at the iteration $1$ is black, the color of $(2,2)$ at the iteration $2$ is black, and the color of $(3,3)$ at the iteration $3$ is also black.

For the second example, you can prove that the cells will never change their colors.

Difficulty: HARD

Solutions:
import sys
input = sys.stdin.readline
(N, M, T) = map(int, input().split())
X = [[0] * M for _ in range(N)]
S = []
for _ in range(N):
	s = input().strip()
	S.append(s)
f = False
stack = []
for i in range(N):
	for j in range(M):
		c = S[i][j]
		for (a, b) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
			if a < 0 or a >= N:
				continue
			if b < 0 or b >= M:
				continue
			if S[a][b] == c:
				X[i][j] = 1
				stack.append((i, j))
				f = True
				break
ss = 1
while stack:
	tmp = []
	ss += 1
	while stack:
		(i, j) = stack.pop()
		for (a, b) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
			if a < 0 or a >= N:
				continue
			if b < 0 or b >= M:
				continue
			if X[a][b] == 0:
				X[a][b] = ss
				tmp.append((a, b))
	stack = tmp
if not f:
	for _ in range(T):
		(i, j, p) = map(int, input().split())
		print(S[i - 1][j - 1])
else:
	for _ in range(T):
		(i, j, p) = map(int, input().split())
		(i, j) = (i - 1, j - 1)
		f = max(0, p - X[i][j] + 1)
		if S[i][j] == '1':
			print(1 - f % 2)
		else:
			print(f % 2)


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7

def build_grid(H, W, intv, _type, space=True, padding=False):
	if space:
		_input = lambda : input().split()
	else:
		_input = lambda : input()
	_list = lambda : list(map(_type, _input()))
	if padding:
		offset = 1
	else:
		offset = 0
	grid = list2d(H + offset * 2, W + offset * 2, intv)
	for i in range(offset, H + offset):
		row = _list()
		for j in range(offset, W + offset):
			grid[i][j] = row[j - offset]
	return grid

def bfs(grid, src):
	from collections import deque
	(H, W) = (len(grid), len(grid[0]))
	directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
	dist = list2d(H, W, -1)
	que = deque()
	for (h, w) in src:
		que.append((h, w, 0))
		dist[h][w] = 0
	while que:
		(h, w, c) = que.popleft()
		for (dh, dw) in directions:
			h2 = h + dh
			w2 = w + dw
			if grid[h2][w2] == -1:
				continue
			if dist[h2][w2] != -1:
				continue
			dist[h2][w2] = c + 1
			que.append((h2, w2, c + 1))
	return dist
(H, W, Q) = MAP()
grid = build_grid(H, W, -1, int, space=0, padding=1)
src = []
for i in range(1, H + 1):
	for j in range(1, W + 1):
		if grid[i][j] == grid[i + 1][j] or grid[i][j] == grid[i - 1][j] or grid[i][j] == grid[i][j + 1] or (grid[i][j] == grid[i][j - 1]):
			src.append((i, j))
res = bfs(grid, src)
for i in range(Q):
	(h, w, p) = MAP()
	if res[h][w] == -1 or p <= res[h][w]:
		ans = grid[h][w]
	else:
		ans = grid[h][w] + p - res[h][w] & 1
	print(ans)


import sys
import math
from collections import defaultdict, deque

def check(i, j):
	return 0 <= i < n and 0 <= j < m
(n, m, t) = map(int, sys.stdin.readline().split())
grid = []
for i in range(n):
	s = list(sys.stdin.readline()[:-1])
	grid.append(s)
grid0 = [[-1 for _ in range(m)] for x in range(n)]
q = deque()
dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for i in range(n):
	for j in range(m):
		z = False
		for (a, b) in dirs:
			(x, y) = (a + i, b + j)
			if check(x, y) and grid[x][y] == grid[i][j]:
				z = True
				break
		if z:
			q.append([i, j, 0])
			grid0[i][j] = 0
while q:
	(a, b, dis) = q.popleft()
	for (i, j) in dirs:
		(x, y) = (a + i, b + j)
		if check(x, y) and grid0[x][y] == -1:
			grid0[x][y] = dis + 1
			q.append([x, y, dis + 1])
for _ in range(t):
	(i, j, p) = map(int, sys.stdin.readline().split())
	i -= 1
	j -= 1
	p -= 1
	if p < grid0[i][j] or grid0[i][j] == -1:
		print(grid[i][j])
		sys.stdout.flush()
	else:
		p -= grid0[i][j]
		if p % 2 == 0:
			print(str(int(grid[i][j]) ^ 1))
			sys.stdout.flush()
		else:
			print(grid[i][j])
			sys.stdout.flush()


from sys import stdin
from collections import deque
(n, m, t) = map(int, stdin.readline().split())
tablero = [input() for _ in range(n)]
infinite = 10 ** 6
d = [[infinite] * m for _ in range(n)]
direcciones = [(-1, 0), (0, -1), (1, 0), (0, 1)]
Q = deque()
for i in range(n):
	for j in range(m):
		for (d_i, d_j) in direcciones:
			n_i = i + d_i
			n_j = j + d_j
			if n_i >= n or n_i < 0 or n_j >= m or (n_j < 0):
				continue
			if tablero[n_i][n_j] == tablero[i][j]:
				d[i][j] = 1
				Q.append((i, j))
				break
while Q:
	(i, j) = Q.popleft()
	for (d_i, d_j) in direcciones:
		n_i = i + d_i
		n_j = j + d_j
		if n_i >= n or n_i < 0 or n_j >= m or (n_j < 0):
			continue
		if d[n_i][n_j] == infinite:
			d[n_i][n_j] = d[i][j] + 1
			Q.append((n_i, n_j))
for _ in range(t):
	(i, j, p) = map(int, stdin.readline().split())
	i = i - 1
	j = j - 1
	if d[i][j] == infinite or p < d[i][j]:
		print(tablero[i][j])
	elif d[i][j] % 2 == p % 2:
		print(1 - int(tablero[i][j]))
	else:
		print(tablero[i][j])


printn = lambda x: print(x, end='')
import sys
input = sys.stdin.readline
inn = lambda : int(input())
inl = lambda : list(map(int, input().split()))
inm = lambda : map(int, input().split())
ins = lambda : input().strip()
DBG = True and False
BIG = 10 ** 18
R = 10 ** 9 + 7
from collections import deque

def ddprint(x):
	if DBG:
		print(x)

class Unionfind:

	def __init__(s, n):
		s.sz = [1] * n
		s.ances = [i for i in range(n)]

	def root(s, x):
		a = []
		y = x
		while s.ances[y] != y:
			a.append(y)
			y = s.ances[y]
		for z in a:
			s.ances[z] = y
		return y

	def conn(s, x, y):
		i = s.root(x)
		j = s.root(y)
		if i == j:
			return
		k = j if s.sz[i] < s.sz[j] else i
		if k == j:
			s.ances[i] = j
		else:
			s.ances[j] = i
		s.sz[k] = s.sz[i] + s.sz[j]
(n, m, t) = inm()
a = []
for i in range(n):
	a.append(ins())
uf = Unionfind(n * m)
for i in range(n):
	for j in range(m):
		if j < m - 1 and a[i][j] == a[i][j + 1]:
			uf.conn(i * m + j, i * m + j + 1)
		if i < n - 1 and a[i][j] == a[i + 1][j]:
			uf.conn(i * m + j, (i + 1) * m + j)
h = [0] * (n * m)
for i in range(n):
	for j in range(m):
		r = uf.root(i * m + j)
		h[r] += 1
nsingles = h.count(1)
if nsingles == n * m:
	for tt in range(t):
		(i, j, p) = inm()
		print(a[i - 1][j - 1])
	exit()
future = [[None] * m for i in range(n)]
q = deque([])
for i in range(n):
	for j in range(m):
		r = uf.root(i * m + j)
		if h[r] > 1:
			future[i][j] = (0, r)
			q.append((i, j))
while len(q) > 0:
	(i, j) = q.popleft()
	(d, r) = future[i][j]
	for dir in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
		x = i + dir[0]
		y = j + dir[1]
		if 0 <= x < n and 0 <= y < m and (future[x][y] is None):
			future[x][y] = (d + 1, r)
			q.append((x, y))
			if False:
				for dir in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
					xx = x + dir[0]
					yy = y + dir[1]
					if 0 <= xx < n and 0 <= yy < m and (future[xx][yy] is None) and (a[x][y] != a[xx][yy]):
						future[xx][yy] = (d + 2, r)
						q.append((xx, yy))
if DBG:
	for i in range(n):
		print(future[i])
for tt in range(t):
	(i, j, p) = inm()
	i -= 1
	j -= 1
	(d, r) = future[i][j]
	if p < d:
		print(a[i][j])
	else:
		ri = r // m
		rj = r % m
		print(a[ri][rj] if p % 2 == 0 else 1 - int(a[ri][rj]))


import io
import os
from collections import Counter, defaultdict, deque

def tup(r, c):
	return r * 1024 + c

def untup(t):
	return divmod(t, 1024)

def solve(R, C, grid, queries):

	def getNbr(node):
		(r, c) = untup(node)
		for (dr, dc) in [(-1, 0), (0, -1), (0, 1), (1, 0)]:
			nr = r + dr
			nc = c + dc
			if 0 <= nr < R and 0 <= nc < C:
				yield (nr, nc)
	dp = {}
	q = deque()
	for r in range(R):
		for c in range(C):
			node = tup(r, c)
			if any((grid[nr][nc] == grid[r][c] for (nr, nc) in getNbr(node))):
				dp[node] = 0
				q.append(node)
	if not dp:
		return '\n'.join((grid[r - 1][c - 1] for (r, c, t) in queries))
	while q:
		node = q.popleft()
		t = dp[node]
		for (nr, nc) in getNbr(node):
			nbr = tup(nr, nc)
			if nbr not in dp:
				dp[nbr] = t + 1
				q.append(nbr)
	ans = []
	for (r, c, t) in queries:
		r -= 1
		c -= 1
		ans.append(str((int(grid[r][c]) + max(0, t - dp[tup(r, c)])) % 2))
	return '\n'.join(ans)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, M, T) = [int(x) for x in input().split()]
grid = [input().decode().rstrip() for r in range(N)]
queries = [[int(x) for x in input().split()] for i in range(T)]
ans = solve(N, M, grid, queries)
print(ans)


def main():
	import sys, math
	from heapq import heapify, heappush, heappop
	from collections import defaultdict as dd, deque, Counter

	def data():
		return sys.stdin.readline().strip()

	def mdata():
		return list(map(int, data().split()))

	def out(*var, end='\n'):
		sys.stdout.write('\n'.join(map(str, var)) + end)
	INF = float('inf')
	mod = int(1000000000.0) + 7
	(n, m, t) = mdata()
	mat = []
	vis = [[INF] * m for i in range(n)]
	q = deque()
	steps = [(-1, 0), (0, -1), (1, 0), (0, 1)]
	for i in range(n):
		mat.append(list(map(int, list(data()))))
	for i in range(n):
		for j in range(m):
			for (k, l) in steps:
				if n > i + k >= 0 and m > j + l >= 0 and (mat[i][j] == mat[i + k][j + l]):
					q.append([i, j])
					vis[i][j] = 0
					break
	while q:
		(x, y) = q.popleft()
		for (k, l) in steps:
			if n > x + k >= 0 and m > y + l >= 0 and (vis[x][y] + 1 < vis[x + k][y + l]):
				q.append([x + k, y + l])
				vis[x + k][y + l] = vis[x][y] + 1
	ans = []
	for i in range(t):
		(i, j, p) = mdata()
		i -= 1
		j -= 1
		if vis[i][j] >= p:
			ans.append(mat[i][j])
		else:
			k = p - vis[i][j]
			if k % 2 == 0:
				ans.append(mat[i][j])
			else:
				ans.append(1 - mat[i][j])
	out(*ans)
main()


from collections import deque
(n, m, t) = [int(x) for x in input().split()]
a = []
b = []
for _ in range(n):
	a.append(input())
	b.append([-1 for _ in range(m)])
q = deque()
for i in range(n):
	for j in range(m):
		c = a[i][j]
		if i > 0 and a[i - 1][j] == c or (i < n - 1 and a[i + 1][j] == c) or (j > 0 and a[i][j - 1] == c) or (j < m - 1 and a[i][j + 1] == c):
			b[i][j] = 0
			q.appendleft((i, j))
if not q:
	for _ in range(t):
		(i, j, p) = [int(x) for x in input().split()]
		i -= 1
		j -= 1
		print(a[i][j])
	exit()
while q:
	(i, j) = q.pop()
	v = b[i][j]
	if i > 0 and b[i - 1][j] == -1:
		b[i - 1][j] = v + 1
		q.appendleft((i - 1, j))
	if i < n - 1 and b[i + 1][j] == -1:
		b[i + 1][j] = v + 1
		q.appendleft((i + 1, j))
	if j > 0 and b[i][j - 1] == -1:
		b[i][j - 1] = v + 1
		q.appendleft((i, j - 1))
	if j < m - 1 and b[i][j + 1] == -1:
		b[i][j + 1] = v + 1
		q.appendleft((i, j + 1))
for _ in range(t):
	(i, j, p) = [int(x) for x in input().split()]
	i -= 1
	j -= 1
	p -= b[i][j]
	if p < 0 or p % 2 == 0:
		print(a[i][j])
	else:
		print('1' if a[i][j] == '0' else '0')


import os
import sys
if os.path.exists('/mnt/c/Users/Square/square/codeforces'):
	f = iter(open('E.txt').readlines())

	def input():
		return next(f)
else:
	input = lambda : sys.stdin.readline().rstrip()
from collections import deque

def main():
	(n, m, t) = map(int, input().split())
	A = [input() for _ in range(n)]
	T = [0] * (n * m)
	d = ((1, 0), (0, 1), (-1, 0), (0, -1))
	stack = deque()
	for ij in range(n * m):
		(i, j) = (ij // m, ij % m)
		for (dx, dy) in d:
			if 0 <= i + dx < n and 0 <= j + dy < m and (A[i][j] == A[i + dx][j + dy]):
				T[ij] = 1
				stack.append(ij)
	while stack:
		ij = stack.popleft()
		(i, j) = (ij // m, ij % m)
		for (dx, dy) in d:
			k = (i + dx) * m + j + dy
			if 0 <= i + dx < n and 0 <= j + dy < m and (T[k] == 0):
				T[k] = T[ij] + 1
				stack.append(k)
	zero = ord('0')
	for _ in range(t):
		(i, j, p) = map(int, input().split())
		i -= 1
		j -= 1
		ij = i * m + j
		if T[ij] == 0:
			print(A[i][j])
		elif p > T[ij] - 1:
			p -= T[ij] - 1
			print((p + ord(A[i][j]) - zero) % 2)
		else:
			print(A[i][j])
main()


import sys
import collections

def main():
	input = lambda : sys.stdin.readline().rstrip()
	(n, m, t) = map(int, input().split())
	T = [input() for _ in range(n)]
	C = [0] * (n * m)
	d = ((1, 0), (0, 1), (-1, 0), (0, -1))
	Q = collections.deque()
	for ij in range(n * m):
		(i, j) = (ij // m, ij % m)
		for (dx, dy) in d:
			if 0 <= i + dx < n and 0 <= j + dy < m and (T[i][j] == T[i + dx][j + dy]):
				C[ij] = 1
				Q.append(ij)
				break
		else:
			continue
	while Q:
		q = Q.popleft()
		(i, j) = (q // m, q % m)
		for (dx, dy) in d:
			if 0 <= i + dx < n and 0 <= j + dy < m and (C[(i + dx) * m + j + dy] == 0):
				C[(i + dx) * m + j + dy] = C[q] + 1
				Q.append((i + dx) * m + j + dy)
	for _ in range(t):
		(i, j, p) = map(int, input().split())
		i -= 1
		j -= 1
		if C[i * m + j] > 0 and max(0, p + 1 - C[i * m + j]) % 2 == 1:
			if T[i][j] == '0':
				print(1)
			else:
				print(0)
		elif T[i][j] == '0':
			print(0)
		else:
			print(1)
main()


from queue import deque

def main():
	(n, m, t) = readIntArr()
	grid = []
	for _ in range(n):
		grid.append(input())
	firstChange = [[-1 for _ in range(m)] for __ in range(n)]
	d4i = [0, -1, 0, 1]
	d4j = [-1, 0, 1, 0]
	q = deque()
	for i in range(n):
		for j in range(m):
			for z in range(4):
				ii = i + d4i[z]
				jj = j + d4j[z]
				if 0 <= ii < n and 0 <= jj < m and (grid[ii][jj] == grid[i][j]):
					q.append([i, j, 0])
					firstChange[i][j] = 0
					break
	if len(q) == 0:
		stable = True
	else:
		stable = False
		while q:
			(i, j, nTurns) = q.popleft()
			for z in range(4):
				ii = i + d4i[z]
				jj = j + d4j[z]
				if 0 <= ii < n and 0 <= jj < m and (firstChange[ii][jj] == -1):
					firstChange[ii][jj] = nTurns + 1
					q.append([ii, jj, nTurns + 1])
	allAns = []
	for _ in range(t):
		(i, j, p) = readIntArr()
		i -= 1
		j -= 1
		if stable or p <= firstChange[i][j]:
			allAns.append(grid[i][j])
		else:
			parityChange = (p - firstChange[i][j]) % 2
			allAns.append((parityChange + int(grid[i][j])) % 2)
	multiLineArrayPrint(allAns)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()


import sys

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline()[:-1]

def main():
	inf = 10 ** 18 + 5
	(h, w, t) = MI()
	aa = [[int(c) for c in SI()] for _ in range(h)]
	bb = [[0] * w for _ in range(h)]
	for i in range(h):
		for j in range(w):
			ind = True
			if i - 1 >= 0 and aa[i][j] == aa[i - 1][j]:
				ind = False
			if i + 1 < h and aa[i][j] == aa[i + 1][j]:
				ind = False
			if j - 1 >= 0 and aa[i][j] == aa[i][j - 1]:
				ind = False
			if j + 1 < w and aa[i][j] == aa[i][j + 1]:
				ind = False
			if ind:
				bb[i][j] = inf
	for i in range(h):
		for j in range(1, w):
			if bb[i][j] == 0:
				continue
			bb[i][j] = min(bb[i][j - 1] + 1, bb[i][j])
		for j in range(w - 2, -1, -1):
			if bb[i][j] == 0:
				continue
			bb[i][j] = min(bb[i][j + 1] + 1, bb[i][j])
	for j in range(w):
		for i in range(1, h):
			if bb[i][j] == 0:
				continue
			bb[i][j] = min(bb[i - 1][j] + 1, bb[i][j])
		for i in range(h - 2, -1, -1):
			if bb[i][j] == 0:
				continue
			bb[i][j] = min(bb[i + 1][j] + 1, bb[i][j])
	for _ in range(t):
		(i, j, p) = MI()
		(i, j) = (i - 1, j - 1)
		p -= bb[i][j]
		if p <= 0:
			print(aa[i][j])
		else:
			rev = p % 2
			print(aa[i][j] ^ rev)
main()


import sys
input = lambda : sys.stdin.readline().rstrip()
from collections import deque
(n, m, t) = map(int, input().split())
B = [[int(a) for a in input()] for _ in range(n)]
Q = deque([])
D = [-1] * (n * m)
for x in range(n * m):
	(i, j) = (x // m, x % m)
	v = B[i][j]
	if i and B[i - 1][j] == v or (i < n - 1 and B[i + 1][j] == v) or (j and B[i][j - 1] == v) or (j < m - 1 and B[i][j + 1] == v):
		D[x] = 0
		Q.append(x)
if len(Q) != len(D):
	while Q:
		x = Q.popleft()
		(i, j) = (x // m, x % m)
		for (di, dj) in ((0, 1), (0, -1), (1, 0), (-1, 0)):
			(ni, nj) = (i + di, j + dj)
			if 0 <= ni < n and 0 <= nj < m:
				y = ni * m + nj
				if D[y] == -1:
					D[y] = D[x] + 1
					Q.append(y)
if D[0] < 0:
	D = [10 ** 18] * (n * m)
for _ in range(t):
	(i, j, p) = map(int, input().split())
	(i, j) = (i - 1, j - 1)
	x = i * m + j
	print(B[i][j] if max(p - D[x], 0) % 2 == 0 else B[i][j] ^ 1)


import sys
input = lambda : sys.stdin.readline().rstrip()
from collections import deque
(H, W, T) = map(int, input().split())
Y = [[int(a) for a in input()] for _ in range(H)]
Q = deque([])
D = [-1] * (H * W)
for x in range(H * W):
	(i, j) = (x // W, x % W)
	y = Y[i][j]
	if i and Y[i - 1][j] == y or (i < H - 1 and Y[i + 1][j] == y) or (j and Y[i][j - 1] == y) or (j < W - 1 and Y[i][j + 1] == y):
		D[x] = 0
		Q.append(x)
while Q:
	x = Q.popleft()
	(i, j) = (x // W, x % W)
	for (di, dj) in ((0, 1), (0, -1), (1, 0), (-1, 0)):
		(ni, nj) = (i + di, j + dj)
		if 0 <= ni < H and 0 <= nj < W:
			y = ni * W + nj
			if D[y] == -1:
				D[y] = D[x] + 1
				Q.append(y)
if D[0] < 0:
	D = [10 ** 18] * (H * W)
for _ in range(T):
	(i, j, p) = map(int, input().split())
	(i, j) = (i - 1, j - 1)
	x = i * W + j
	print(Y[i][j] if max(p - D[x], 0) % 2 == 0 else Y[i][j] ^ 1)


import collections

class Mapping2D:

	def __init__(self, *arg):
		self.none = object()
		try:
			iterable = iter(arg[0])
			self.a = [list(row) for row in iterable]
			self.dim = (len(self.a), len(self.a[0]))
			assert all((len(row) == self.dim[1] for row in self.a))
			self.len = self.dim[0] * self.dim[1]
		except TypeError:
			self.dim = arg
			self.a = [[self.none] * self.dim[1] for _ in range(self.dim[0])]
			self.len = 0

	def __repr__(self):
		return 'Mapping2D({})'.format(repr(self.a))

	def __len__(self):
		return self.len

	def inbounds(self, u):
		return 0 <= u[0] < self.dim[0] and 0 <= u[1] < self.dim[1]

	def __contains__(self, u):
		return self.inbounds(u) and self.a[u[0]][u[1]] is not self.none

	def __getitem__(self, u):
		if u not in self:
			raise KeyError(u)
		return self.a[u[0]][u[1]]

	def __setitem__(self, u, x):
		if not self.inbounds(u):
			raise KeyError(u)
		if u not in self:
			self.len += 1
		self.a[u[0]][u[1]] = x

	def __delitem__(self, u):
		if not self.inbounds(u):
			raise KeyError(u)
		if u in self:
			self.len -= 1
			self.a[u[0]][u[1]] = self.none

	def get(self, u, default=None):
		if u in self:
			return self[u]
		else:
			return default

	def update(self, iterable):
		for (u, x) in iterable:
			self[u] = x

	def clear(self):
		self.__init__(self.dim[0], self.dim[1])

	def items(self):
		for i in range(self.dim[0]):
			for j in range(self.dim[1]):
				x = self.a[i][j]
				if x is self.none:
					continue
				yield ((i, j), x)

	def keys(self):
		return (k for (k, _) in self.items())

	def values(self):
		return (v for (_, v) in self.items())

	def __iter__(self):
		return self.keys()

	def __eq__(self, other):
		return isinstance(other, Mapping2D) and self.a == other.a

	@staticmethod
	def _dmoves(u):
		D_PAD = ((-1, 0), (0, -1), (0, 1), (1, 0))
		return ((u[0] + d[0], u[1] + d[1]) for d in D_PAD)

	def neighbors(self, u):
		return (v for v in self._dmoves(u) if self.inbounds(v))
if False:
	import doctest
	doctest.testmod()
import sys

def input(itr=iter(sys.stdin.readlines())):
	return next(itr).rstrip('\n\r')
import collections
import itertools
import math
(n, m, t) = map(int, input().split())
grid = Mapping2D(((int(c) for c in input()) for _ in range(n)))

def active(u):
	return any((grid[v] == grid[u] for v in grid.neighbors(u)))
still_life = Mapping2D(n, m)
queue = collections.deque()
for u in itertools.product(range(n), range(m)):
	if active(u):
		still_life[u] = 0
		queue.append(u)
while queue:
	u = queue.popleft()
	for v in grid.neighbors(u):
		if v not in still_life:
			still_life[v] = still_life[u] + 1
			queue.append(v)

def status(u, p):
	s = still_life.get(u, math.inf)
	if p <= s:
		return grid[u]
	else:
		return grid[u] ^ p - s & 1
output = []
for _ in range(t):
	(i, j, p) = map(int, input().split())
	output.append(status((i - 1, j - 1), p))
print(*output, sep='\n')


def main():
	import sys
	from array import array
	from collections import deque
	input = sys.stdin.readline
	(H, W, Q) = map(int, input().split())
	grid = array('b', [0] * (H * W))
	for h in range(H):
		line = input().rstrip('\n')
		for w in range(W):
			if line[w] == '1':
				grid[h * W + w] ^= 1
	que = deque()
	start_change = [-1] * (H * W)
	d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
	for h in range(H):
		for w in range(W):
			same = 0
			hw = h * W + w
			for (dh, dw) in d:
				(h_new, w_new) = (h + dh, w + dw)
				hw_new = h_new * W + w_new
				if 0 <= h_new < H and 0 <= w_new < W:
					if grid[hw] == grid[hw_new]:
						same = 1
						break
			if same:
				que.append(hw)
				start_change[hw] = 0
	while que:
		hw = que.popleft()
		(h, w) = divmod(hw, W)
		for (dh, dw) in d:
			(h_new, w_new) = (h + dh, w + dw)
			hw_new = h_new * W + w_new
			if 0 <= h_new < H and 0 <= w_new < W:
				if start_change[hw_new] == -1:
					start_change[hw_new] = start_change[hw] + 1
					que.append(hw_new)
	for _ in range(Q):
		(h, w, p) = map(int, input().split())
		h -= 1
		w -= 1
		hw = h * W + w
		if start_change[hw] == -1:
			print(grid[hw])
			continue
		if p <= start_change[hw]:
			print(grid[hw])
		elif (p - start_change[hw]) % 2 == 0:
			print(grid[hw])
		else:
			print(grid[hw] ^ 1)
main()


from sys import stdin
input = stdin.readline
(r, c, t) = map(int, input().split())
mat = [list(map(int, list(input()[:c]))) for i in range(r)]
for i in range(r):
	for j in range(c):
		if (j + i) % 2 == 0:
			mat[i][j] = (mat[i][j] + 1) % 2

def nbrs(a, b):
	out = []
	if a > 0:
		out.append([a - 1, b])
	if a < r - 1:
		out.append([a + 1, b])
	if b > 0:
		out.append([a, b - 1])
	if b < c - 1:
		out.append([a, b + 1])
	return out
odl = [[-1] * c for i in range(r)]
start0 = []
start1 = []
for rr in range(r):
	for cc in range(c):
		if mat[rr][cc] == 0:
			for k in nbrs(rr, cc):
				if mat[k[0]][k[1]] == 1:
					start0.append([rr, cc])
					break
		else:
			for k in nbrs(rr, cc):
				if mat[k[0]][k[1]] == 0:
					start1.append([rr, cc])
for i in start0:
	odl[i[0]][i[1]] = 1
ind0 = 0
while ind0 < len(start0):
	cur = start0[ind0]
	ind0 += 1
	for nn in nbrs(cur[0], cur[1]):
		if odl[nn[0]][nn[1]] == -1 and mat[nn[0]][nn[1]] == 0:
			odl[nn[0]][nn[1]] = odl[cur[0]][cur[1]] + 1
			start0.append(nn)
for i in start1:
	odl[i[0]][i[1]] = 1
ind1 = 0
while ind1 < len(start1):
	cur = start1[ind1]
	ind1 += 1
	for nn in nbrs(cur[0], cur[1]):
		if odl[nn[0]][nn[1]] == -1 and mat[nn[0]][nn[1]] == 1:
			odl[nn[0]][nn[1]] = odl[cur[0]][cur[1]] + 1
			start1.append(nn)
for _ in range(t):
	(rr, cc, p) = map(int, input().split())
	rr -= 1
	cc -= 1
	if odl[0][0] == -1:
		print((mat[rr][cc] + rr + cc + 1) % 2)
	elif p < odl[rr][cc]:
		print((mat[rr][cc] + rr + cc + 1) % 2)
	else:
		print((mat[rr][cc] + rr + cc + odl[rr][cc] + p) % 2)


from collections import deque
(n, m, t) = map(int, input().split())
s = []
for _ in range(n):
	s.append(input())
query = []
for _ in range(t):
	(i, j, p) = map(int, input().split())
	query.append((i - 1, j - 1, p))
dist = [[-1] * m for _ in range(n)]
q = deque()
dxdy = [(-1, 0), (0, -1), (0, 1), (1, 0)]
for y in range(n):
	for x in range(m):
		for (dx, dy) in dxdy:
			if not (0 <= x + dx < m and 0 <= y + dy < n):
				continue
			if s[y][x] == s[y + dy][x + dx]:
				dist[y][x] = 0
				q.append((y, x))
				break
while q:
	(y, x) = q.popleft()
	for (dx, dy) in dxdy:
		if not (0 <= x + dx < m and 0 <= y + dy < n):
			continue
		if dist[y + dy][x + dx] >= 0:
			continue
		dist[y + dy][x + dx] = dist[y][x] + 1
		q.append((y + dy, x + dx))
for (y, x, p) in query:
	if dist[y][x] < 0 or p - dist[y][x] < 0:
		print(s[y][x])
	else:
		print((int(s[y][x]) + p - dist[y][x]) % 2)


import sys
input = sys.stdin.readline
from collections import deque
dp = [[0 for i in range(10 ** 3 + 2)] for j in range(10 ** 3 + 2)]
vis = [[0 for i in range(10 ** 3 + 2)] for j in range(10 ** 3 + 2)]

def check(i, j):
	if i > 0:
		if a[i][j] == a[i - 1][j]:
			return True
	if j > 0:
		if a[i][j] == a[i][j - 1]:
			return True
	if i < n - 1:
		if a[i][j] == a[i + 1][j]:
			return True
	if j < m - 1:
		if a[i][j] == a[i][j + 1]:
			return True
	return False
pq = [[-1, 0], [1, 0], [0, -1], [0, 1]]

def bfs():
	q = deque()
	for i in range(n):
		for j in range(m):
			if check(i, j):
				q.append([i, j, 0])
				vis[i][j] = 1
	while len(q) != 0:
		z = q.popleft()
		for g in pq:
			i = z[0] + g[0]
			j = z[1] + g[1]
			if 0 <= i <= n - 1 and 0 <= j < m and (vis[i][j] == 0):
				vis[i][j] = 1
				dp[i][j] = z[2] + 1
				q.append([i, j, dp[i][j]])
(n, m, qq) = map(int, input().split())
a = []
for i in range(n):
	p = list(input().rstrip())
	a.append(p)
bfs()
for i in range(qq):
	(x, y, p) = map(int, input().split())
	x -= 1
	y -= 1
	yy = max(0, p - dp[x][y])
	yy = yy & 1
	if vis[x][y]:
		print(int(a[x][y]) ^ yy)
	else:
		print(a[x][y])


import sys
input = sys.stdin.readline
(n, m, t) = map(int, input().split())
board = [0] * n
change = [0] * n
for i in range(n):
	board[i] = [0] * m
	change[i] = [-1] * m
	s = input()
	for j in range(m):
		if s[j] == '1':
			board[i][j] = 1
tod = []
for i in range(n):
	for j in range(m):
		if change[i][j] == -1:
			c = -1
			if i > 0:
				if board[i - 1][j] == board[i][j]:
					c = 0
			if i < n - 1:
				if board[i + 1][j] == board[i][j]:
					c = 0
			if j > 0:
				if board[i][j - 1] == board[i][j]:
					c = 0
			if j < m - 1:
				if board[i][j + 1] == board[i][j]:
					c = 0
			if c == 0:
				change[i][j] = 0
				tod.append([i, j])
c = 0
while len(tod) > 0:
	tod2 = []
	for ij in tod:
		i = ij[0]
		j = ij[1]
		if change[i][j] == -1 or c == 0:
			change[i][j] = c
			if i > 0:
				if change[i - 1][j] == -1:
					tod2.append([i - 1, j])
			if i < n - 1:
				if change[i + 1][j] == -1:
					tod2.append([i + 1, j])
			if j > 0:
				if change[i][j - 1] == -1:
					tod2.append([i, j - 1])
			if j < m - 1:
				if change[i][j + 1] == -1:
					tod2.append([i, j + 1])
	c += 1
	tod = tod2
for f in range(t):
	(i, j, p) = map(int, input().split())
	i -= 1
	j -= 1
	if change[i][j] == -1 or change[i][j] > p:
		print(board[i][j])
	else:
		p -= change[i][j]
		p += board[i][j]
		p %= 2
		print(p)


import sys
from collections import deque
input = sys.stdin.readline
print = sys.stdout.write
(n, m, t) = map(int, input().split())
B = [[-1 for i in range(m)] for j in range(n)]
A = []
for i in range(n):
	A.append(input())
C = deque([])
for i in range(n):
	for j in range(m):
		if i > 0 and A[i - 1][j] == A[i][j] or (j > 0 and A[i][j - 1] == A[i][j]) or (i < n - 1 and A[i + 1][j] == A[i][j]) or (j < m - 1 and A[i][j + 1] == A[i][j]):
			B[i][j] = 0
			C.append([i, j])
while len(C) != 0:
	iv = C.popleft()
	(i, j) = (iv[0], iv[1])
	val = B[i][j]
	if i > 0 and B[i - 1][j] == -1:
		B[i - 1][j] = val + 1
		C.append([i - 1, j])
	if j > 0 and B[i][j - 1] == -1:
		B[i][j - 1] = val + 1
		C.append([i, j - 1])
	if i < n - 1 and B[i + 1][j] == -1:
		B[i + 1][j] = val + 1
		C.append([i + 1, j])
	if j < m - 1 and B[i][j + 1] == -1:
		B[i][j + 1] = val + 1
		C.append([i, j + 1])
for i in range(t):
	(p, q, r) = map(int, input().split())
	(p, q) = (p - 1, q - 1)
	if B[p][q] == -1 or r <= B[p][q]:
		print(A[p][q] + '\n')
	elif (B[p][q] - r) % 2 == 0:
		print(A[p][q] + '\n')
	else:
		print(str(int(A[p][q]) ^ 1) + '\n')


import sys
from collections import deque
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	(n, m, t) = nm()
	g = [list(map(int, list(input()))) for _ in range(n)]
	b = [[10 ** 18 + 5] * m for _ in range(n)]
	q = deque()
	for i in range(n):
		for j in range(m):
			if j < m - 1 and g[i][j] == g[i][j + 1]:
				b[i][j] = b[i][j + 1] = 0
			if i < n - 1 and g[i][j] == g[i + 1][j]:
				b[i][j] = b[i + 1][j] = 0
			if b[i][j] == 0:
				q.append(i * m + j)
	while q:
		v = q.popleft()
		(y, x) = divmod(v, m)
		for (ny, nx) in [(y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)]:
			if 0 <= ny < n and 0 <= nx < m and (b[ny][nx] > b[y][x] + 1):
				b[ny][nx] = b[y][x] + 1
				q.append(ny * m + nx)
	for _ in range(t):
		(y, x, p) = nm()
		y -= 1
		x -= 1
		if b[y][x] >= p:
			print(g[y][x])
		else:
			print(g[y][x] ^ p - b[y][x] & 1)
	return
solve()


import sys
from collections import deque
input = sys.stdin.readline
(n, m, t) = map(int, input().split())
grid = [input().strip() for i in range(n)]
dist = [[-1] * m for i in range(n)]
q = deque()
for i in range(n):
	for j in range(m):
		current = grid[i][j]
		for (k, l) in [[i - 1, j], [i, j - 1], [i + 1, j], [i, j + 1]]:
			if k >= 0 and k < n and (l >= 0) and (l < m) and (grid[k][l] == current):
				dist[i][j] = 1
				q.append((i, j))
while q:
	(i, j) = q.pop()
	for (k, l) in [[i - 1, j], [i, j - 1], [i + 1, j], [i, j + 1]]:
		if k >= 0 and k < n and (l >= 0) and (l < m) and (dist[k][l] == -1):
			dist[k][l] = dist[i][j] + 1
			q.appendleft((k, l))
for z in range(t):
	(i, j, turn) = map(int, input().split())
	i -= 1
	j -= 1
	if turn < dist[i][j] or dist[i][j] == -1:
		print(int(grid[i][j]))
		continue
	if turn % 2 != dist[i][j] % 2:
		print(int(grid[i][j]))
		continue
	if grid[i][j] == '1':
		print(0)
		continue
	print(1)


(N, M, T) = map(int, input().split())
G = [list(input()) for _ in range(N)]
FF = [[-1] * M for _ in range(N)]
mov = [(1, 0), (-1, 0), (0, 1), (0, -1)]
Q = []
missing = N * M
for (y, l) in enumerate(G):
	for (x, c) in enumerate(l):
		for (dx, dy) in mov:
			nx = x + dx
			ny = y + dy
			if nx < 0 or ny < 0 or nx >= M or (ny >= N):
				continue
			if c == G[ny][nx]:
				FF[y][x] = 1
				Q.append((x, y))
				break
while Q:
	NQ = []
	for (x, y) in Q:
		mf = FF[y][x]
		for (dx, dy) in mov:
			nx = x + dx
			ny = y + dy
			if nx < 0 or ny < 0 or nx >= M or (ny >= N):
				continue
			if FF[ny][nx] == -1:
				FF[ny][nx] = mf + 1
				NQ.append((nx, ny))
	Q = NQ

def opp(c):
	return '1' if c == '0' else '0'
for _ in range(T):
	(i, j, p) = map(int, input().split())
	i -= 1
	j -= 1
	if p < FF[i][j] or FF[i][j] == -1:
		print(G[i][j])
	else:
		print(G[i][j] if (p - FF[i][j]) % 2 == 1 else opp(G[i][j]))


import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
import heapq as h, time
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def getInt():
	return int(input())

def getStrs():
	return input().split()

def getInts():
	return list(map(int, input().split()))

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def getBin():
	return list(map(int, list(input())))

def isInt(s):
	return '0' <= s[0] <= '9'

def ceil_(a, b):
	return a // b + (a % b > 0)
MOD = 10 ** 9 + 7

def solve():
	(N, M, T) = getInts()
	G = []
	for _ in range(N):
		G += getBin()
	size = N * M
	par = [-1] * size
	level = [-1] * size
	queue = dq([])

	def f(x):
		if x - M >= 0 and G[x - M] == G[x]:
			return True
		if x + M < size and G[x + M] == G[x]:
			return True
		if x % M and G[x - 1] == G[x]:
			return True
		if (x + 1) % M and G[x + 1] == G[x]:
			return True
		return False
	for i in range(N * M):
		if f(i):
			par[i] = G[i]
			level[i] = 0
			queue.append(i)
	while queue:
		node = queue.popleft()
		ops = []
		if node - M >= 0:
			ops.append(node - M)
		if node + M < size:
			ops.append(node + M)
		if node % M:
			ops.append(node - 1)
		if (node + 1) % M:
			ops.append(node + 1)
		for neigh in ops:
			if par[neigh] == -1:
				par[neigh] = par[node]
				level[neigh] = level[node] + 1
				queue.append(neigh)
	for _ in range(T):
		(i, j, p) = getInts()
		i -= 1
		j -= 1
		node = i * M + j
		if par[node] == -1:
			print(G[node])
		elif p < level[node]:
			print(G[node])
		else:
			print(par[node] ^ p % 2)
	return
solve()


import sys
input = sys.stdin.readline
(n, m, t) = map(int, input().split())
cell = [list(input().rstrip()) for _ in range(n)]
cnt = [[False] * m for _ in range(n)]
for i in range(n):
	for j in range(m):
		if i - 1 >= 0 and cell[i - 1][j] == cell[i][j]:
			cnt[i][j] = True
		if i + 1 < n and cell[i + 1][j] == cell[i][j]:
			cnt[i][j] = True
		if j - 1 >= 0 and cell[i][j - 1] == cell[i][j]:
			cnt[i][j] = True
		if j + 1 < m and cell[i][j + 1] == cell[i][j]:
			cnt[i][j] = True
num = 0
cur = []
dp = [None] * n * m
for i in range(n):
	for j in range(m):
		if cnt[i][j]:
			dp[i + n * j] = 0
			cur.append(i + n * j)
			num += 1
if num > 0:
	while None in dp:
		temp = cur
		cur = []
		for x in temp:
			(i, j) = (x % n, x // n)
			if i - 1 >= 0 and dp[x - 1] is None:
				dp[x - 1] = dp[x] + 1
				cur.append(x - 1)
			if i + 1 < n and dp[x + 1] is None:
				dp[x + 1] = dp[x] + 1
				cur.append(x + 1)
			if j - 1 >= 0 and dp[x - n] is None:
				dp[x - n] = dp[x] + 1
				cur.append(x - n)
			if j + 1 < m and dp[x + n] is None:
				dp[x + n] = dp[x] + 1
				cur.append(x + n)
for _ in range(t):
	(i, j, p) = map(int, input().split())
	i -= 1
	j -= 1
	if cnt[i][j]:
		print((int(cell[i][j]) + p) % 2)
	else:
		if num == 0:
			print(cell[i][j])
			continue
		if dp[i + n * j] > p:
			print(cell[i][j])
		else:
			p -= dp[i + n * j]
			print((int(cell[i][j]) + p) % 2)


import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
(N, M, T) = map(int, input().split())
A = []
for i in range(N):
	A.append([int(x) for x in list(input())])
good = [[False for _ in range(M)] for _ in range(N)]
goods = []
for r in range(N):
	for c in range(M):
		for (nr, nc) in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
			if 0 <= nr < N and 0 <= nc < M and (A[nr][nc] == A[r][c]):
				good[r][c] = True
				goods.append((r, c))
				break
INF = float('inf')
dist = [[INF for _ in range(M)] for _ in range(N)]
for (r, c) in goods:
	dist[r][c] = 0
q = goods
d = 0
while q:
	nq = []
	for (r, c) in q:
		for (nr, nc) in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
			if 0 <= nr < N and 0 <= nc < M and (dist[nr][nc] > d + 1):
				dist[nr][nc] = d + 1
				nq.append((nr, nc))
	q = nq
	d += 1
ans = []
for ti in range(T):
	(i, j, p) = map(int, input().split())
	i -= 1
	j -= 1
	d = dist[i][j]
	if d > p:
		ans.append(A[i][j])
	else:
		p -= d
		ans.append(A[i][j] if p % 2 == 0 else A[i][j] ^ 1)
print('\n'.join(map(str, ans)))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=300006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.height = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val == 0:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
			elif val >= 1:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left

	def do(self, temp):
		if not temp:
			return 0
		ter = temp
		temp.height = self.do(ter.left) + self.do(ter.right)
		if temp.height == 0:
			temp.height += 1
		return temp.height

	def query(self, xor):
		self.temp = self.root
		cur = 0
		i = 31
		while i > -1:
			val = xor & 1 << i
			if not self.temp:
				return cur
			if val >= 1:
				self.opp = self.temp.right
				if self.temp.left:
					self.temp = self.temp.left
				else:
					return cur
			else:
				self.opp = self.temp.left
				if self.temp.right:
					self.temp = self.temp.right
				else:
					return cur
			if self.temp.height == pow(2, i):
				cur += 1 << i
				self.temp = self.opp
			i -= 1
		return cur
(n, m, k) = map(int, input().split())
s = []
for i in range(n):
	s.append(list(input()))
dp = [[1000000 for i in range(m)] for j in range(n)]
for i in range(n):
	for j in range(m):
		if i >= 1:
			if s[i][j] == s[i - 1][j]:
				dp[i][j] = 0
			else:
				dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1)
		if j >= 1:
			if s[i][j] == s[i][j - 1]:
				dp[i][j] = 0
			else:
				dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1)
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if i < n - 1:
			if s[i][j] == s[i + 1][j]:
				dp[i][j] = 0
			else:
				dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1)
		if j < m - 1:
			if s[i][j] == s[i][j + 1]:
				dp[i][j] = 0
			else:
				dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1)
for i in range(k):
	(i, j, p) = map(int, input().split())
	i -= 1
	j -= 1
	if dp[i][j] >= 1000000:
		print(s[i][j])
	else:
		ans = p - dp[i][j]
		if ans <= 0:
			print(s[i][j])
			continue
		ans %= 2
		if ans == 1:
			print(1 - int(s[i][j]))
		else:
			print(s[i][j])


from sys import stdin, gettrace
from array import array
from copy import deepcopy
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():
	(n, m, t) = map(int, input().split())
	grid = []
	for _ in range(n):
		grid.append(array('B', map(int, list(input()))))
	ogrid = deepcopy(grid)
	gstart = [array('h', [-1] * m) for _ in range(n)]
	glistr = array('h')
	glistc = array('h')
	for j in range(n):
		for k in range(m):
			c = grid[j][k]
			if k > 0 and c == grid[j][k - 1] or (j > 0 and c == grid[j - 1][k]) or (k < m - 1 and c == grid[j][k + 1]) or (j < n - 1 and c == grid[j + 1][k]):
				gstart[j][k] = 1
				glistr.append(j)
				glistc.append(k)
	i = 1
	while glistr:
		i += 1
		nglistr = array('h')
		nglistc = array('h')
		for (j, k) in zip(glistr, glistc):
			if k > 0 and gstart[j][k - 1] == -1:
				gstart[j][k - 1] = i
				nglistr.append(j)
				nglistc.append(k - 1)
			if j > 0 and gstart[j - 1][k] == -1:
				gstart[j - 1][k] = i
				nglistr.append(j - 1)
				nglistc.append(k)
			if k < m - 1 and gstart[j][k + 1] == -1:
				gstart[j][k + 1] = i
				nglistr.append(j)
				nglistc.append(k + 1)
			if j < n - 1 and gstart[j + 1][k] == -1:
				gstart[j + 1][k] = i
				nglistr.append(j + 1)
				nglistc.append(k)
		glistr = nglistr
		glistc = nglistc
	for q in range(t):
		(i, j, p) = map(int, input().split())
		gs = gstart[i - 1][j - 1]
		if gs == -1 or gs > p or (p - gs) % 2 == 1:
			print(ogrid[i - 1][j - 1])
		else:
			print(1 - ogrid[i - 1][j - 1])
main()


from sys import stdin, stdout
import sys
from math import *
input = stdin.readline
(n, m, t) = map(int, input().split())
ar = []
dp = []
x = -1
y = -1
for i in range(n):
	ar.append(input())
	dp.append([inf] * m)
from collections import deque
q1 = deque()
q2 = deque()
for i in range(n):
	for j in range(m):
		if j > 0:
			if ar[i][j] == ar[i][j - 1]:
				dp[i][j] = 0
				q1.append(i)
				q2.append(j)
				if x == -1:
					(x, y) = (i, j)
		if j < m - 1:
			if ar[i][j] == ar[i][j + 1]:
				dp[i][j] = 0
				q1.append(i)
				q2.append(j)
				if x == -1:
					(x, y) = (i, j)
		if i > 0:
			if ar[i - 1][j] == ar[i][j]:
				dp[i][j] = 0
				q1.append(i)
				q2.append(j)
				if x == -1:
					(x, y) = (i, j)
		if i < n - 1:
			if ar[i + 1][j] == ar[i][j]:
				dp[i][j] = 0
				q1.append(i)
				q2.append(j)
				if x == -1:
					(x, y) = (i, j)
if x != -1:
	while len(q1) != 0:
		x = q1.popleft()
		y = q2.popleft()
		if x > 0 and dp[x - 1][y] == inf:
			dp[x - 1][y] = min(dp[x - 1][y], 1 + dp[x][y])
			q1.append(x - 1)
			q2.append(y)
		if x < n - 1 and dp[x + 1][y] == inf:
			dp[x + 1][y] = min(dp[x + 1][y], 1 + dp[x][y])
			q1.append(x + 1)
			q2.append(y)
		if y > 0 and dp[x][y - 1] == inf:
			dp[x][y - 1] = min(dp[x][y - 1], 1 + dp[x][y])
			q1.append(x)
			q2.append(y - 1)
		if y < m - 1 and dp[x][y + 1] == inf:
			dp[x][y + 1] = min(dp[x][y + 1], 1 + dp[x][y])
			q1.append(x)
			q2.append(y + 1)
	for i in range(t):
		(a, b, c) = map(int, input().split())
		a -= 1
		b -= 1
		if dp[a][b] == 0:
			if c % 2 == 0:
				print(ar[a][b])
			elif ar[a][b] == '1':
				print('0')
			else:
				print('1')
		elif dp[a][b] + 1 > c:
			print(ar[a][b])
		elif dp[a][b] % 2 == 1:
			if c % 2 == 1:
				print(ar[a][b])
			else:
				print(int(ar[a][b]) ^ 1)
		elif c % 2 == 0:
			print(ar[a][b])
		else:
			print(int(ar[a][b]) ^ 1)
else:
	for i in range(t):
		(a, b, c) = map(int, input().split())
		print(ar[a - 1][b - 1])


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None

def lcm(a, b):
	return a * b // gcd(a, b)
t = 1
for i in range(t):
	(n, m, t) = RL()
	a = []
	for i in range(n):
		a.append(input())
	dp = [[-1] * m for i in range(n)]
	q = deque()
	for i in range(n):
		for j in range(m):
			for (ni, nj) in nb(i, j):
				if a[ni][nj] == a[i][j]:
					dp[i][j] = 0
					q.append([i, j])
					break
	if not q:
		f = False
	else:
		f = True
	cur = 1
	while q:
		for i in range(len(q)):
			(ci, cj) = q.popleft()
			for (ni, nj) in nb(ci, cj):
				if dp[ni][nj] == -1:
					dp[ni][nj] = cur
					q.append([ni, nj])
		cur += 1
	for i in range(t):
		(i, j, p) = RL()
		if f:
			if p <= dp[i - 1][j - 1]:
				print(a[i - 1][j - 1])
			else:
				print(int(a[i - 1][j - 1]) ^ p - dp[i - 1][j - 1] & 1)
		else:
			print(a[i - 1][j - 1])


def main():
	import sys
	input = sys.stdin.buffer.readline
	(N, M, Q) = map(int, input().split())
	state = [list(input().rstrip()) for _ in range(N)]
	Query = [list(map(int, input().split())) for _ in range(Q)]
	Last = [[-1] * M for _ in range(N)]
	Need = [[-1] * M for _ in range(N)]
	q = []
	for n in range(N):
		for m in range(M):
			tmp = state[n][m]
			isStart = False
			if n != 0 and state[n - 1][m] == tmp:
				isStart = True
			if n != N - 1 and state[n + 1][m] == tmp:
				isStart = True
			if m != 0 and state[n][m - 1] == tmp:
				isStart = True
			if m != M - 1 and state[n][m + 1] == tmp:
				isStart = True
			if isStart:
				Need[n][m] = 0
				Last[n][m] = tmp - 48
				q.append((n, m))
	if not q:
		for (n, m, num) in Query:
			print(state[n - 1][m - 1] % 2)
	else:
		while q:
			qq = []
			for (n, m) in q:
				nexts = []
				if n != 0:
					nexts.append((n - 1, m))
				if n != N - 1:
					nexts.append((n + 1, m))
				if m != 0:
					nexts.append((n, m - 1))
				if m != M - 1:
					nexts.append((n, m + 1))
				for (pn, pm) in nexts:
					if Last[pn][pm] == -1:
						Last[pn][pm] = Last[n][m]
						Need[pn][pm] = Need[n][m] + 1
						qq.append((pn, pm))
			q = qq
		for (n, m, num) in Query:
			n -= 1
			m -= 1
			if num < Need[n][m]:
				print(state[n][m] % 2)
			else:
				print((Last[n][m] + num) % 2)
main()


import sys
from collections import deque
readline = sys.stdin.readline
(H, W, T) = map(int, readline().split())
G = [-1] * (W + 2)
for _ in range(H):
	G.extend([-1] + list(map(int, readline().strip())) + [-1])
G.extend([-1] * (W + 2))
geta = W + 2
of1 = set()
DIREC = [1, -1, W + 2, -W - 2]
Q = []
for vn in range((H + 2) * (W + 2)):
	if G[vn] == -1:
		continue
	for dv in DIREC:
		if G[vn] == G[vn + dv]:
			Q.append(vn)
			break
if not Q:
	for qu in range(T):
		(i, j, p) = map(int, readline().split())
		vn = i * geta + j
		sys.stdout.write(str(G[vn]) + '\n')
else:
	dist = [0] * ((H + 2) * (W + 2))
	used = set(Q)
	Q = deque(Q)
	while Q:
		vn = Q.pop()
		for dv in DIREC:
			if G[vn + dv] == -1 or vn + dv in used:
				continue
			used.add(vn + dv)
			dist[vn + dv] = 1 + dist[vn]
			Q.appendleft(vn + dv)
	for qu in range(T):
		(i, j, p) = map(int, readline().split())
		vn = i * geta + j
		if dist[vn] >= p:
			ans = G[vn]
		else:
			ans = G[vn] ^ 1 & p - dist[vn]
		sys.stdout.write(str(ans) + '\n')


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	(n, m, t) = RL()
	arr = []
	rec = [[INF] * m for _ in range(n)]
	qr = []
	dr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
	q = deque()
	for _ in range(n):
		arr.append(list(input()))
	for _ in range(t):
		qr.append(RLL())
	for i in range(n):
		for j in range(m):
			now = arr[i][j]
			for (nx, ny) in dr:
				(xx, yy) = (i + nx, j + ny)
				if -1 < xx < n and -1 < yy < m:
					if arr[xx][yy] == now:
						q.append((i, j, 0))
						rec[i][j] = 0
						break
	while q:
		(x, y, time) = q.popleft()
		for (nx, ny) in dr:
			(xx, yy) = (x + nx, y + ny)
			if -1 < xx < n and -1 < yy < m:
				if rec[xx][yy] == INF:
					q.append((xx, yy, time + 1))
					rec[xx][yy] = min(rec[xx][yy], time + 1)
	for (i, j, time) in qr:
		ori = int(arr[i - 1][j - 1])
		ct = rec[i - 1][j - 1]
		dif = time - ct
		if dif % 2 == 1 and dif > 0:
			ori ^= 1
		print(ori)
main()


import sys
input = sys.stdin.readline
(n, m, t) = map(int, input().split())
MAP = [input().strip() for i in range(n)]
COUNT = [[-1] * m for i in range(n)]
from collections import deque
Q = deque()
for i in range(n):
	for j in range(m):
		for (z, w) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:
			if 0 <= z < n and 0 <= w < m and (MAP[i][j] == MAP[z][w]):
				Q.append((i, j))
				COUNT[i][j] = 1
while Q:
	(i, j) = Q.pop()
	for (z, w) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:
		if 0 <= z < n and 0 <= w < m and (COUNT[z][w] == -1):
			COUNT[z][w] = COUNT[i][j] + 1
			Q.appendleft((z, w))
for tests in range(t):
	(x, y, j) = map(int, input().split())
	x -= 1
	y -= 1
	if COUNT[x][y] == -1 or COUNT[x][y] > j:
		print(int(MAP[x][y]))
	else:
		print((j - COUNT[x][y] + 1 + int(MAP[x][y])) % 2)


from collections import deque
import sys
input = lambda : sys.stdin.readline().rstrip()

def check(r, c):
	for i in range(4):
		if r + dy[i] >= 0 and r + dy[i] < n and (c + dx[i] >= 0) and (c + dx[i] < m):
			if adj[r + dy[i]][c + dx[i]] == adj[r][c]:
				return True
	return False

def valid(r, c):
	return r >= 0 and r < n and (c >= 0) and (c < m)

def bfs():
	q = deque()
	for i in range(n):
		for j in range(m):
			if check(i, j):
				dist[i][j] = 0
				q.append((i, j))
	while len(q) > 0:
		(r, c) = q.popleft()
		for i in range(4):
			(nr, nc) = (r + dx[i], c + dy[i])
			if valid(nr, nc) and dist[nr][nc] > 1 + dist[r][c]:
				dist[nr][nc] = 1 + dist[r][c]
				q.append((nr, nc))
(n, m, t) = map(int, input().split())
(adj, dist) = ([], [[10 ** 18 + 5] * m for _ in range(n)])
(dx, dy) = ([-1, 1, 0, 0], [0, 0, -1, 1])
for _ in range(n):
	adj.append(list(input()))
bfs()
for _ in range(t):
	(i, j, p) = map(int, input().split())
	cur = p - dist[i - 1][j - 1]
	if cur < 0 or cur % 2 == 0:
		cur = adj[i - 1][j - 1]
	else:
		cur = 1 - int(adj[i - 1][j - 1])
	print(cur)


from collections import deque
import sys
input = sys.stdin.readline
(n, m, t) = map(int, input().split())
a = []
for i in range(n):
	a.append(input())
move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
connect = deque([])
dist = [0] * (n * m)
used = [False] * (n * m)
for i in range(n * m):
	h = i // m
	w = i % m
	for (x, y) in move:
		nh = h + x
		nw = w + y
		if n > nh > -1 and m > nw > -1 and (a[h][w] == a[nh][nw]):
			connect.append((i, 0))
			used[i] = True
			break
flag = not connect
while connect:
	(v, d) = connect.popleft()
	if v // m != 0:
		if not used[v - m]:
			used[v - m] = True
			dist[v - m] = d + 1
			connect.append((v - m, d + 1))
	if v // m != n - 1:
		if not used[v + m]:
			used[v + m] = True
			dist[v + m] = d + 1
			connect.append((v + m, d + 1))
	if v % m != 0:
		if not used[v - 1]:
			used[v - 1] = True
			dist[v - 1] = d + 1
			connect.append((v - 1, d + 1))
	if v % m != m - 1:
		if not used[v + 1]:
			used[v + 1] = True
			dist[v + 1] = d + 1
			connect.append((v + 1, d + 1))
for i in range(t):
	(i, j, p) = map(int, input().split())
	v = m * (i - 1) + j - 1
	if not flag:
		if dist[v] >= p:
			print(a[i - 1][j - 1])
		else:
			print((int(a[i - 1][j - 1]) + dist[v] - p) % 2)
	else:
		print(a[i - 1][j - 1])


(n, m, t) = [int(i) for i in input().split()]
grid = [[None for j in range(m)] for i in range(n)]
for i in range(n):
	grid[i] = [0 if i == '0' else 1 for i in input()]
set_up_time = [[None for j in range(m)] for i in range(n)]

def fetch_neighbours(i, j, n, m):
	ans = []
	if i != 0:
		ans.append((i - 1, j))
	if j != 0:
		ans.append((i, j - 1))
	if i != n - 1:
		ans.append((i + 1, j))
	if j != m - 1:
		ans.append((i, j + 1))
	return ans
just_changed = set()
for i in range(n):
	for j in range(m):
		c = grid[i][j]
		if i != 0:
			if grid[i - 1][j] == c:
				set_up_time[i][j] = 0
		if j != 0:
			if grid[i][j - 1] == c:
				set_up_time[i][j] = 0
		if i != n - 1:
			if grid[i + 1][j] == c:
				set_up_time[i][j] = 0
		if j != m - 1:
			if grid[i][j + 1] == c:
				set_up_time[i][j] = 0
		if set_up_time[i][j] is not None:
			just_changed.add((i, j))
degenerate = False
if len(just_changed) == 0:
	degenerate = True
while len(just_changed) != 0:
	new_just_changed = set()
	for (i, j) in just_changed:
		nbrs = fetch_neighbours(i, j, n, m)
		for (i_dash, j_dash) in nbrs:
			if set_up_time[i_dash][j_dash] is None:
				set_up_time[i_dash][j_dash] = 1 + set_up_time[i][j]
				new_just_changed.add((i_dash, j_dash))
			elif set_up_time[i_dash][j_dash] > 1 + set_up_time[i][j]:
				set_up_time[i_dash][j_dash] = 1 + set_up_time[i][j]
				new_just_changed.add((i_dash, j_dash))
	just_changed = new_just_changed
answers = []
for _ in range(t):
	(i, j, p) = [int(i) for i in input().split()]
	i -= 1
	j -= 1
	if degenerate:
		ans = grid[i][j]
	elif p < set_up_time[i][j]:
		ans = grid[i][j]
	else:
		ans = ((p - set_up_time[i][j]) % 2 + grid[i][j]) % 2
	answers.append(ans)
print(*answers, sep='\n')


from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
dir = [-1, 0, 1, 0, -1]
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt

def geti():
	return map(int, input().strip().split())

def getl():
	return list(map(int, input().strip().split()))

def getis():
	return map(str, input().strip().split())

def getls():
	return list(map(str, input().strip().split()))

def gets():
	return input().strip()

def geta():
	return int(input())

def print_s(s):
	stdout.write(s + '\n')

def solve():
	(n, m, q) = geti()
	mat = []
	for i in range(n):
		now = list(map(int, list(gets())))
		mat.append(now)

	def neighbour(i, j, val):
		for d in range(4):
			x = i + dir[d]
			y = j + dir[d + 1]
			if 0 <= x < n and 0 <= y < m and (mat[x][y] == val):
				return True
		return False
	good = deque()
	for i in range(n):
		for j in range(m):
			if neighbour(i, j, mat[i][j]):
				good.append((i, j, 0))
	for (i, j, cost) in good:
		mat[i][j] = [mat[i][j], 0]
	ok = False
	while good:
		ok = True
		(i, j, cost) = good.popleft()
		for d in range(4):
			x = i + dir[d]
			y = j + dir[d + 1]
			if 0 <= x < n and 0 <= y < m:
				try:
					temp = len(mat[x][y])
				except:
					mat[x][y] = [mat[x][y], cost + 1]
					good.append((x, y, cost + 1))
	for i in range(q):
		(a, b, c) = geti()
		a -= 1
		b -= 1
		if not ok:
			print(mat[a][b])
			continue
		if not mat[a][b][1]:
			if c & 1:
				print(mat[a][b][0] ^ 1)
			else:
				print(mat[a][b][0])
		else:
			need = mat[a][b][1]
			if need <= c and c - need & 1:
				print(mat[a][b][0] ^ 1)
			else:
				print(mat[a][b][0])
solve()


import sys
input = sys.stdin.readline
import math
import collections
(n, m, t) = map(int, input().split())
board = []
for i in range(n):
	board.append([int(i) for i in input() if i != '\n'])
start = [[math.inf] * m for _ in range(n)]
visited = [[0] * m for _ in range(n)]
queue = collections.deque()

def bfs1():
	while queue:
		vertex = queue.popleft()
		visited[vertex[0]][vertex[1]] = 1
		for (hor, ver) in [[vertex[0] + 1, vertex[1]], [vertex[0] - 1, vertex[1]], [vertex[0], vertex[1] + 1], [vertex[0], vertex[1] - 1]]:
			if 0 <= hor < n and 0 <= ver < m:
				if visited[hor][ver] == 0:
					start[hor][ver] = min(start[hor][ver], start[vertex[0]][vertex[1]] + 1)
					queue.append([hor, ver])
					visited[hor][ver] = 1
for i in range(n):
	for j in range(m):
		for (z, w) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:
			if 0 <= z < n and 0 <= w < m and (board[i][j] == board[z][w]):
				queue.append((i, j))
				start[i][j] = 1
bfs1()
for i in range(t):
	(i, j, p) = map(int, input().split())
	i -= 1
	j -= 1
	if start[i][j] == -1 or p < start[i][j]:
		print(board[i][j])
	elif (p - start[i][j]) % 2 == 0:
		print((board[i][j] + 1) % 2)
	else:
		print(board[i][j])