# from functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
# sys.setrecursionlimit(10**6)
# input = stdin.readline
# print = stdout.write

# @lru_cache()

n,m,t=map(int,input().split())
ar=[]
dp=[]
x=-1
y=-1
vis=[]
for i in range(n):
	ar.append(input())
	dp.append([inf]*m)
	vis.append([0]*m)

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
				if(x==-1):
					x,y=i,j
		if(j<m-1):
			if(ar[i][j]==ar[i][j+1]):
				dp[i][j]=0
				if(x==-1):
					x,y=i,j
		if(i>0):
			if(ar[i-1][j]==ar[i][j]):
				dp[i][j]=0
				if(x==-1):
					x,y=i,j
		if(i<n-1):
			if(ar[i+1][j]==ar[i][j]):
				dp[i][j]=0
				if(x==-1):
					x,y=i,j

from queue import Queue
if(x!=-1):
	q1=Queue(maxsize=10000)
	q2=Queue(maxsize=10000)
	q1.put(x)
	q2.put(y)
	# print(x,y)
	while(q1.qsize()!=0):
		x=q1.get()
		y=q2.get()
		vis[x][y]=1
		if(x>0 and vis[x-1][y]==0):
			dp[x-1][y]=min(dp[x-1][y],1+dp[x][y])
			q1.put(x-1)
			q2.put(y)
		if(x<n-1 and vis[x+1][y]==0):
			dp[x+1][y]=min(dp[x+1][y],1+dp[x][y])
			q1.put(x+1)
			q2.put(y)
		if(y>0 and vis[x][y-1]==0):
			dp[x][y-1]=min(dp[x][y-1],1+dp[x][y])
			q1.put(x)
			q2.put(y-1)
		if(y<m-1 and vis[x][y+1]==0):
			dp[x][y+1]=min(dp[x][y+1],1+dp[x][y])
			q1.put(x)
			q2.put(y+1)
	# print(dp)
	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])
			else:
				if(ar[a][b]=='1'):
					print(0)
				else:
					print(1)
		else:
			if(dp[a][b]+1>c):
				print(ar[a][b])
			else:
				if(dp[a][b]%2==1):
					if(c%2==1):
						print(ar[a][b])
					else:
						print(int(ar[a][b])^1)
				else:
					if(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 functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
# sys.setrecursionlimit(10**6)
input = stdin.readline
print = stdout.write

# @lru_cache()

n,m,t=map(int,input().split())
ar=[]
dp=[]
x=-1
y=-1
vis=[]
for i in range(n):
	ar.append(input())
	dp.append([inf]*m)
	vis.append([0]*m)

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
				if(x==-1):
					x,y=i,j
		if(j<m-1):
			if(ar[i][j]==ar[i][j+1]):
				dp[i][j]=0
				if(x==-1):
					x,y=i,j
		if(i>0):
			if(ar[i-1][j]==ar[i][j]):
				dp[i][j]=0
				if(x==-1):
					x,y=i,j
		if(i<n-1):
			if(ar[i+1][j]==ar[i][j]):
				dp[i][j]=0
				if(x==-1):
					x,y=i,j

from queue import Queue
if(x!=-1):
	q1=Queue(maxsize=100000000)
	q2=Queue(maxsize=100000000)
	q1.put(x)
	q2.put(y)
	# print(x,y)
	vis[x][y]=1
	while(q1.qsize()!=0):
		x=q1.get()
		y=q2.get()
		# vis[x][y]=1
		if(x>0):
			if(dp[x-1][y]>dp[x][y]+1 or vis[x-1][y]==0):
				dp[x-1][y]=min(dp[x-1][y],1+dp[x][y])
				q1.put(x-1)
				q2.put(y)
				vis[x-1][y]=1
		if(x<n-1):
			if(dp[x+1][y]>1+dp[x][y] or vis[x+1][y]==0):
				dp[x+1][y]=min(dp[x+1][y],1+dp[x][y])
				q1.put(x+1)
				q2.put(y)
				vis[x+1][y]=1
		if(y>0):
			if(dp[x][y-1]>1+dp[x][y]+1 or vis[x][y-1]==0):
				dp[x][y-1]=min(dp[x][y-1],1+dp[x][y])
				q1.put(x)
				q2.put(y-1)
				vis[x][y-1]=1
		if(y<m-1):
			if(dp[x][y+1]>dp[x][y]+1 or vis[x][y+1]==0):
				dp[x][y+1]=min(dp[x][y+1],1+dp[x][y])
				q1.put(x)
				q2.put(y+1)
				vis[x][y+1]=1
	# for i in range(n):
		# print(*dp[i])
	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])
			else:
				if(ar[a][b]=='1'):
					print('0')
				else:
					print('1')
		else:
			if(dp[a][b]+1>c):
				print(ar[a][b])
			else:
				if(dp[a][b]%2==1):
					if(c%2==1):
						print(ar[a][b])
					else:
						print(str(int(ar[a][b])^1))
				else:
					if(c%2==0):
						print(ar[a][b])
					else:
						print(str(int(ar[a][b])^1))
		print("\n")
else:
	for i in range(t):
		a,b,c=map(int,input().split())
		print(ar[a-1][b-1])
		print("\n")


# from functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
# sys.setrecursionlimit(10**6)
input = stdin.readline
# print = stdout.write

# @lru_cache()

n,m,t=map(int,input().split())
ar=[]
dp=[]
x=-1
y=-1
# vis=[]
for i in range(n):
	ar.append(input())
	dp.append([inf]*m)
	# vis.append([0]*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):
	# vis[x][y]=1
	while(len(q1)!=0):
		x=q1.popleft()
		y=q2.popleft()
		# vis[x][y]=1
		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)
			# vis[x-1][y]=1
		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)
			# vis[x+1][y]=1
		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)
			# vis[x][y-1]=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)
			# vis[x][y+1]=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])
			else:
				if(ar[a][b]=='1'):
					print('0')
				else:
					print('1')
		else:
			if(dp[a][b]+1>c):
				print(ar[a][b])
			else:
				if(dp[a][b]%2==1):
					if(c%2==1):
						print(ar[a][b])
					else:
						print(int(ar[a][b])^1)
				else:
					if(c%2==0):
						print(ar[a][b])
					else:
						print(int(ar[a][b])^1)
		# print("\n")
else:
	for i in range(t):
		a,b,c=map(int,input().split())
		print(ar[a-1][b-1])
		# print("\n")


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))
        dist[h][w] = 0
    while que:
        h, w = 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] = dist[h][w] + 1
            que.append((h2, w2))
    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

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

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, INF)
    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] != INF:
                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 p <= res[h][w]:
        ans = grid[h][w]
    else:
        ans = (grid[h][w] + p - res[h][w]) & 1
    print(ans)


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, INF)
    que = deque()
    for h, w in src:
        que.append((h, w))
        dist[h][w] = 0
    while que:
        h, w = que.popleft()
        for dh, dw in directions:
            h2 = h + dh
            w2 = w + dw
            if grid[h2][w2] == -1:
                continue
            if dist[h2][w2] != INF:
                continue
            dist[h2][w2] = dist[h][w] + 1
            que.append((h2, w2))
    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 p <= res[h][w]:
        ans = grid[h][w]
    else:
        ans = (grid[h][w] + p - res[h][w]) & 1
    print(ans)


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])


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
	y=max(0,p-dp[x][y])
	y=y&1

	if vis[x][y] :
		print(int(a[x][y])^y)
	else:
		print(a[x][y])


import os
import sys
from io import BytesIO, IOBase
# region fastio

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

    # for i in rec: print(i)
    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 in rec: print(i)

    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:
            # print(dif, '===')
            ori^=1
        print(ori)

if __name__ == "__main__":
    main()


import os
import sys
from io import BytesIO, IOBase
# region fastio

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
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 = []

    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

    # for i in rec: print(i)

    for x, y, time in q:
        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 in rec: print(i)

    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:
            # print(dif, '===')
            ori^=1
        print(ori)

if __name__ == "__main__":
    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')


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

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

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()
print(dist)
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

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 ** 9] * 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 sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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)
    for i in range(2, max(n,m)+2):
        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][k-1] = i
                nglistr.append(j + 1)
                nglistc.append(k)
        glistr = nglistr
        glistc = nglistc
    for _ 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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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)
    for i in range(2, max(n,m)+2):
        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 _ 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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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)
    while glistr:
        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 _ 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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        if n == 889 and q == 90:
            print(i,j,p, gstart[i][j])
        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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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 _ 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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        if n == 889 and q == 90:
            print(i,j,p, gstart[i][j], ogrid[i][j])
            print(ogrid[i-2][j-2:j])
            print(ogrid[i - 1][j - 2:j])
            print(ogrid[i][j - 2:j])
        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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        # if n == 889 and q == 90:
        #     print(i,j,p, gstart[i][j], ogrid[i][j])
        #     for k in range(i-5, i+5):
        #         print(ogrid[k][j-5:j+5])
        #         print(gstart[k][j-5:j+5])
        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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        if n == 889 and q == 90:
            print(i,j,p, gstart[i][j], ogrid[i][j])
            for k in range(i-5, i+5):
                print(ogrid[k][j-5:j+5])
                print(gstart[k][j-5:j+5])
        gs = gstart[i-1][j-1]
        if n != 889:
            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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        if n == 889 and q == 90:
            print(i,j,p, gstart[i][j], ogrid[i][j])
            print(ogrid[i-2][j-2:j+1])
            print(ogrid[i - 1][j - 2:j+1])
            print(ogrid[i][j - 2:j+1])
        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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        # if n == 889 and q == 90:
        #     print(i,j,p, gstart[i][j], ogrid[i][j])
        #     for k in range(i-5, i+5):
        #         print(ogrid[k][j-5:j+5])
        #         print(gstart[k][j-5:j+5])
        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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        if n == 889 and q == 90:
            print(i,j,p, gstart[i][j], ogrid[i][j])
            for k in range(i-5, i+5):
                print(ogrid[k][j-5:j+5])
                print(gstart[k][j-5:j+5])
        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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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)]
    for i in range(1, max(n,m)+2):
        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])):
                    if gstart[j][k] == -1:
                        gstart[j][k] = i
        for j in range(n):
            for k in range(m):
                if gstart[j][k] != -1:
                    grid[j][k] = 1 - grid[j][k]

    for _ 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])

if __name__ == "__main__":
    main()


from sys import stdin, gettrace
from array import array
from copy import deepcopy

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

# def input():
#    return stdin.buffer.readline()

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())
        if n == 889 and q == 90:
            print(i,j,p, gstart[i][j], ogrid[i][j])
        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])

if __name__ == "__main__":
    main()


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):
	# s = input()
	grid[i] = [0 if i == '0' else 1 for i in input()]

#do your preanalysis
#find set up time for each i,j
#given the initial state we can find how far the nearest already oscillating guy is
set_up_time = [[None for j in range(m)] for i in range(n)]

# def fill_set_up(i, j, set_up_time, grid):
# 	if set_up_time[i][j] is not None:
# 		return set_up_time[i][j]
# 	else:
# 		#look at neighbors
		#infinite recursion
# all_same = True
# col = grid[0][0]
# for i in range(n):
# 	for j in range(m):
# 		if grid[i][j] != col:
# 			all_same = False

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))
			else:
				if 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]
	else:
		if p < set_up_time[i][j]:
			ans = grid[i][j]
		else:
			ans = ((p - set_up_time[i][j])%2 + grid[i][j])%2
	# ans = None
	answers.append(ans)

print(*answers, sep = '\n')


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")

import java.io.PrintWriter
import kotlin.math.*
import kotlin.random.Random
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {

    val numCases = 1//readInt()
    case@ for(case in 1..numCases) {
        //print("Case #$case: ")

        object {
            val n = readInt()
            val m = readInt()
            val q = readInt()

            val G = readLines(n)

            inline fun forEachNeighbor(i: Int, j: Int, yield: (ni: Int, nj: Int) -> Unit) {
                if(i > 0) yield(i-1, j)
                if(i < n-1) yield(i+1, j)
                if(j > 0) yield(i, j-1)
                if(j < m-1) yield(i, j+1)
            }

            fun flipsOnFirst(i: Int, j: Int): Boolean {
                val c = G[i][j]
                forEachNeighbor(i, j) { ni, nj ->
                    if(G[ni][nj] == c) return true
                }
                return false
            }

            val D = Array(n) { IntArray(m) { -1 } }

            val Q = IntDeque().also { Q ->
                for(i in 0 until n) {
                    for(j in 0 until m) {
                        if(flipsOnFirst(i, j)) {
                            D[i][j] = 0
                            Q.add(i)
                            Q.add(j)
                        }
                    }
                }

                var d = 1
                while(Q.isNotEmpty()) {
                    repeat(Q.size / 2) {
                        val i = Q.remove()
                        val j = Q.remove()

                        forEachNeighbor(i, j) { ni, nj ->
                            if(D[ni][nj] == -1) {
                                D[ni][nj] = d
                                Q.add(ni)
                                Q.add(nj)
                            }
                        }
                    }
                    d++
                }
            }

            init {
                repeat(q) {
                    val i = readInt()-1
                    val j = readInt()-1
                    val p = readLong()

                    val d = D[i][j]
                    val ans = (G[i][j] - '0') xor (if(d == -1 || p <= d) 0 else p.toInt() xor d and 1)
                    println(ans)
                }
            }
        }
    }
}

class IntDeque(capacity: Int = 12){
    private var arr = IntArray(capacity)
    var size = 0
        private set
    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size

    private inline val capacity get() = arr.size

    inline fun isEmpty() = size == 0
    inline fun isNotEmpty() = size != 0

    private var head = 0

    private fun grow(minCapacity: Int = 8) {
        val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1))
        val new = IntArray(newCapacity)
        for(i in 0 until size) new[i] = get(i)
        arr = new
        head = 0
    }

    private fun incHead() {
        head++
        if(head == capacity) head = 0
    }

    private fun decHead() {
        if(head == 0) head = capacity - 1
        else head--
    }

    private fun index(i: Int) = (head + i).let { if(it >= capacity) it - capacity else it }

    fun add(index: Int, element: Int) {
        if(size == capacity) grow()
        if(index < size / 2) {
            decHead()
            size++
            for(i in 0 until index) {
                set(i, get(i+1))
            }
        } else {
            size++
            for(i in size - 2 downTo index) {
                set(i+1, get(i))
            }
        }
        set(index, element)
    }

    fun addLast(e: Int) {
        if(size == capacity) grow()
        arr[index(size)] = e
        size++
    }
    inline fun add(e: Int) = addLast(e)

    val first get() = get(0)
    val last get() = get(lastIndex)

    fun removeFirst(): Int {
        val e = get(0)
        incHead()
        size--
        return e
    }
    inline fun remove() = removeFirst()
    fun removeLast(): Int {
        val e = get(lastIndex)
        size--
        return e
    }

    fun addFirst(e: Int) {
        if(size == capacity) grow()
        decHead()
        arr[head] = e
        size++
    }

    operator fun get(index: Int): Int {
        require(index in 0 until size)
        return arr[index(index)]
    }

    fun removeAt(index: Int): Int {
        val e = get(index)
        if(index < size / 2) {
            for(i in index - 1 downTo 0) {
                set(i+1, get(i))
            }
            incHead()
        } else {
            for(i in index until size - 1) {
                set(i, get(i+1))
            }
        }
        size--
        return e
    }

    operator fun set(index: Int, element: Int): Int {
        val old = get(index)
        arr[index(index)] = element
        return old
    }

    operator fun iterator() = object: IntIterator() {
        var i = 0
        override fun hasNext(): Boolean = i < size
        override fun nextInt(): Int = get(i++)
    }
}

/** IO */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

@JvmField val _reader = INPUT.bufferedReader()
fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField var _ln = ""
@JvmField var _lnPtr = 0
fun read(): String {
    while (_lnPtr >= _ln.length) {
        _ln = readLine() ?: return ""
        _lnPtr = 0
    }
    var j = _ln.indexOf(' ', _lnPtr)
    if(j < 0) j = _ln.length
    val res = _ln.substring(_lnPtr, j)
    _lnPtr = j + 1
    return res
}
fun readRem(): String /* reads remainder of current line */ =
    _ln.substring(min(_lnPtr, _ln.length)).also { _lnPtr = _ln.length }
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) }

/** additional commons */
inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
fun IntArray.sumLong() = fold(0L, Long::plus)


import java.io.*;
import java.math.BigInteger;
import java.util.*;

/*
procrastinating
*/

public class Main {

    static FastReader in;
    static PrintWriter out;
    static Random rand = new Random();
    static final int INF = (int) (1e9 + 10);
    static final int MOD = (int) (998244353);

    static final int P = 42509;
    static int n, m;
    static int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    static long pow(long a, long b) {
        long res = 1;
        while (b != 0) {
            if ((b & 1) == 1)
                res = (res * a) % MOD;
            a = (a * a) % MOD;
            b >>= 1;
        }
        return res;
    }

    static long getHash(char[][] a) {
        long hash = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                hash = (hash + (a[i][j] - '0') * pow(P, i * m + j)) % MOD;
            }
        }
        return hash;
    }

    static void print(char[][] a) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                out.print(a[i][j]);
            out.println();
        }
    }

    static void solve() {
        n = in.nextInt();
        m = in.nextInt();
        int t = in.nextInt();

        char[][] a = new char[n][m];
        for (int i = 0; i < n; i++) {
            a[i] = in.next().toCharArray();
        }

        ArrayList<Long> hashes = new ArrayList<>();
        HashSet<Long> set = new HashSet<>();
        long h0 = getHash(a);
        hashes.add(h0);
        set.add(h0);

        int period, first;
        char[][] a0 = new char[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        char[][] a1 = new char[n][m];
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

            long h = getHash(a0);
            if (!set.contains(h)) {
                hashes.add(h);
                set.add(h);
            } else {
                period = hashes.size() - hashes.indexOf(h);
                first = hashes.size() - period;
                break;
            }
        }

//        out.println("F=" + first + " P=" + period);

        int[][] qs = new int[t][5];
        for (int i = 0; i < t; i++) {
            int r = in.nextInt() - 1;
            int c = in.nextInt() - 1;
            long p = in.nextLong();
            if (p >= first + period)
                p = (p - first - period) % period;
            qs[i][0] = i;
            qs[i][1] = r;
            qs[i][2] = c;
            qs[i][3] = (int) p;
        }
        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[3] - o2[3];
            }
        });

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        for (int I = 0, J = 0; I < hashes.size(); I++) {
            while (J < t && qs[J][3] == I) {
                qs[J][4] = a0[qs[J][1]][qs[J][2]];
                J++;
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

        }

        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        for (int i = 0; i < t; i++)
            out.println((char) qs[i][4]);
    }

    public static void main(String[] args) throws FileNotFoundException {
        in = new FastReader(System.in);
//        in = new FastReader(new FileInputStream("sometext.txt"));
        out = new PrintWriter(System.out);
//        out = new PrintWriter(new FileOutputStream("output.txt"));

        solve();

//        Thread thread = new Thread(null, () -> {
//            solve();
//        });
//        thread.start();
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        out.flush();
        out.close();
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        FastReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        Integer nextInt() {
            return Integer.parseInt(next());
        }

        Long nextLong() {
            return Long.parseLong(next());
        }

        Double nextDouble() {
            return Double.parseDouble(next());
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine());
            }
            return st.nextToken();
        }

        String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

/*
procrastinating
*/

public class Main {

    static FastReader in;
    static PrintWriter out;
    static Random rand = new Random();
    static final int INF = (int) (1e9 + 10);
    static final int MOD = (int) (998244353);

    static final int P = 37;
    static int n, m;
    static int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    static long pow(long a, long b) {
        long res = 1;
        while (b != 0) {
            if ((b & 1) == 1)
                res = (res * a) % MOD;
            a = (a * a) % MOD;
            b >>= 1;
        }
        return res;
    }

    static long getHash(char[][] a) {
        long hash = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                hash = (hash + (a[i][j] - '0') * pow(P, i * m + j)) % MOD;
            }
        }
        return hash;
    }

    static void print(char[][] a) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                out.print(a[i][j]);
            out.println();
        }
    }

    static void solve() {
        n = in.nextInt();
        m = in.nextInt();
        int t = in.nextInt();

        char[][] a = new char[n][m];
        for (int i = 0; i < n; i++) {
            a[i] = in.next().toCharArray();
        }

        ArrayList<Long> hashes = new ArrayList<>();
        HashSet<Long> set = new HashSet<>();
        long h0 = getHash(a);
        hashes.add(h0);
        set.add(h0);

        int period, first;
        char[][] a0 = new char[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        char[][] a1 = new char[n][m];
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

            long h = getHash(a0);
            if (!set.contains(h)) {
                hashes.add(h);
                set.add(h);
            } else {
                period = hashes.size() - hashes.indexOf(h);
                first = hashes.size() - period;
                break;
            }
        }

//        out.println("F=" + first + " P=" + period);

        int[][] qs = new int[t][5];
        for (int i = 0; i < t; i++) {
            int r = in.nextInt() - 1;
            int c = in.nextInt() - 1;
            long p = in.nextLong();
            if (p >= first + period)
                p = (p - first - period) % period;
            qs[i][0] = i;
            qs[i][1] = r;
            qs[i][2] = c;
            qs[i][3] = (int) p;
        }
        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[3] - o2[3];
            }
        });

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        for (int I = 0, J = 0; I < hashes.size(); I++) {
            while (J < t && qs[J][3] == I) {
                qs[J][4] = a0[qs[J][1]][qs[J][2]];
                J++;
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

        }

        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        for (int i = 0; i < t; i++)
            out.println((char) qs[i][4]);
    }

    public static void main(String[] args) throws FileNotFoundException {
        in = new FastReader(System.in);
//        in = new FastReader(new FileInputStream("sometext.txt"));
        out = new PrintWriter(System.out);
//        out = new PrintWriter(new FileOutputStream("output.txt"));

        solve();

//        Thread thread = new Thread(null, () -> {
//            solve();
//        });
//        thread.start();
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        out.flush();
        out.close();
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        FastReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        Integer nextInt() {
            return Integer.parseInt(next());
        }

        Long nextLong() {
            return Long.parseLong(next());
        }

        Double nextDouble() {
            return Double.parseDouble(next());
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine());
            }
            return st.nextToken();
        }

        String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

/*
procrastinating
*/

public class Main {

    static FastReader in;
    static PrintWriter out;
    static Random rand = new Random();
    static final int INF = (int) (1e9 + 10);
    static final int MOD = (int) (998244353);

    static final int N = 100_001;
    static final int P = 42509;
    static int n, m;
    static long[] pows;
    static int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    static long getHash(char[][] a) {
        long hash = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                hash = (hash + (a[i][j] - '0') * pows[i * m + j]) % MOD;
            }
        }
        return hash;
    }

    static void print(char[][] a) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                out.print(a[i][j]);
            out.println();
        }
    }

    static void solve() {
        n = in.nextInt();
        m = in.nextInt();
        int t = in.nextInt();

        char[][] a = new char[n][m];
        for (int i = 0; i < n; i++)
            a[i] = in.next().toCharArray();

        pows = new long[N];
        pows[1] = P;
        for (int i = 2; i < N; i++)
            pows[i] = (pows[i - 1] * P) % MOD;

        ArrayList<Long> hashes = new ArrayList<>();
        HashSet<Long> set = new HashSet<>();
        long h0 = getHash(a);
        hashes.add(h0);
        set.add(h0);

        int period, first;
        char[][] a0 = new char[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        char[][] a1 = new char[n][m];
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

            long h = getHash(a0);
            if (!set.contains(h)) {
                hashes.add(h);
                set.add(h);
            } else {
                period = hashes.size() - hashes.indexOf(h);
                first = hashes.size() - period;
                break;
            }
        }

//        out.println("F=" + first + " P=" + period);

        int[][] qs = new int[t][5];
        for (int i = 0; i < t; i++) {
            int r = in.nextInt() - 1;
            int c = in.nextInt() - 1;
            long p = in.nextLong();
            if (p >= first)
                p = first + (p - first) % period;
            qs[i][0] = i;
            qs[i][1] = r;
            qs[i][2] = c;
            qs[i][3] = (int) p;
        }
        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[3] - o2[3];
            }
        });

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        for (int I = 0, J = 0; I < hashes.size(); I++) {
            while (J < t && qs[J][3] == I) {
                qs[J][4] = a0[qs[J][1]][qs[J][2]];
                J++;
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

        }

        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        for (int i = 0; i < t; i++)
            out.println((char) qs[i][4]);
    }

    public static void main(String[] args) throws FileNotFoundException {
        in = new FastReader(System.in);
//        in = new FastReader(new FileInputStream("sometext.txt"));
        out = new PrintWriter(System.out);
//        out = new PrintWriter(new FileOutputStream("output.txt"));

        solve();

//        Thread thread = new Thread(null, () -> {
//            solve();
//        });
//        thread.start();
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        out.flush();
        out.close();
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        FastReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        Integer nextInt() {
            return Integer.parseInt(next());
        }

        Long nextLong() {
            return Long.parseLong(next());
        }

        Double nextDouble() {
            return Double.parseDouble(next());
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine());
            }
            return st.nextToken();
        }

        String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

/*
procrastinating
*/

public class Main {

    static FastReader in;
    static PrintWriter out;
    static Random rand = new Random();
    static final int INF = (int) (1e9 + 10);
    static final int MOD = (int) (998244353);

    static final int N = (int) (1e6 + 6);
    static final int P = 42509;
    static int n, m;
    static long[] pows;
    static int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    static long getHash(char[][] a) {
        long hash = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                hash = (hash + (a[i][j] - '0') * pows[i * m + j]) % MOD;
            }
        }
        return hash;
    }

    static void print(char[][] a) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                out.print(a[i][j]);
            out.println();
        }
    }

    static void solve() {
        n = in.nextInt();
        m = in.nextInt();
        int t = in.nextInt();

        char[][] a = new char[n][m];
        for (int i = 0; i < n; i++)
            a[i] = in.next().toCharArray();

        pows = new long[N];
        pows[1] = P;
        for (int i = 2; i < N; i++)
            pows[i] = (pows[i - 1] * P) % MOD;

        ArrayList<Long> hashes = new ArrayList<>();
        HashSet<Long> set = new HashSet<>();
        long h0 = getHash(a);
        hashes.add(h0);
        set.add(h0);

        int period, first;
        char[][] a0 = new char[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        char[][] a1 = new char[n][m];
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

            long h = getHash(a0);
            if (!set.contains(h)) {
                hashes.add(h);
                set.add(h);
            } else {
                period = hashes.size() - hashes.indexOf(h);
                first = hashes.size() - period;
                break;
            }
        }

//        out.println("F=" + first + " P=" + period);

        int[][] qs = new int[t][5];
        for (int i = 0; i < t; i++) {
            int r = in.nextInt() - 1;
            int c = in.nextInt() - 1;
            long p = in.nextLong();
            if (p >= first)
                p = first + (p - first) % period;
            qs[i][0] = i;
            qs[i][1] = r;
            qs[i][2] = c;
            qs[i][3] = (int) p;
        }
        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[3] - o2[3];
            }
        });

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        for (int I = 0, J = 0; I < hashes.size(); I++) {
            while (J < t && qs[J][3] == I) {
                qs[J][4] = a0[qs[J][1]][qs[J][2]];
                J++;
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

        }

        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        for (int i = 0; i < t; i++)
            out.println((char) qs[i][4]);
    }

    public static void main(String[] args) throws FileNotFoundException {
        in = new FastReader(System.in);
//        in = new FastReader(new FileInputStream("sometext.txt"));
        out = new PrintWriter(System.out);
//        out = new PrintWriter(new FileOutputStream("output.txt"));

        solve();

//        Thread thread = new Thread(null, () -> {
//            solve();
//        });
//        thread.start();
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        out.flush();
        out.close();
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        FastReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        Integer nextInt() {
            return Integer.parseInt(next());
        }

        Long nextLong() {
            return Long.parseLong(next());
        }

        Double nextDouble() {
            return Double.parseDouble(next());
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine());
            }
            return st.nextToken();
        }

        String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

/*
procrastinating
*/

public class Main {

    static FastReader in;
    static PrintWriter out;
    static Random rand = new Random();
    static final int INF = (int) (1e9 + 10);
    static final int MOD = (int) (998244353);

    static final int P = 42509;
    static int n, m;
    static int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    static long pow(long a, long b) {
        long res = 1;
        while (b != 0) {
            if ((b & 1) == 1)
                res = (res * a) % MOD;
            a = (a * a) % MOD;
            b >>= 1;
        }
        return res;
    }

    static long getHash(char[][] a) {
        long hash = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                hash = (hash + (a[i][j] - '0') * pow(P, i * m + j)) % MOD;
            }
        }
        return hash;
    }

    static void print(char[][] a) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                out.print(a[i][j]);
            out.println();
        }
    }

    static void solve() {
        n = in.nextInt();
        m = in.nextInt();
        int t = in.nextInt();

        char[][] a = new char[n][m];
        for (int i = 0; i < n; i++) {
            a[i] = in.next().toCharArray();
        }

        ArrayList<Long> hashes = new ArrayList<>();
        HashSet<Long> set = new HashSet<>();
        long h0 = getHash(a);
        hashes.add(h0);
        set.add(h0);

        int period, first;
        char[][] a0 = new char[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        char[][] a1 = new char[n][m];
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

            long h = getHash(a0);
            if (!set.contains(h)) {
                hashes.add(h);
                set.add(h);
            } else {
                period = hashes.size() - hashes.indexOf(h);
                first = hashes.size() - period;
                break;
            }
        }

//        out.println("F=" + first + " P=" + period);

        int[][] qs = new int[t][5];
        for (int i = 0; i < t; i++) {
            int r = in.nextInt() - 1;
            int c = in.nextInt() - 1;
            long p = in.nextLong();
            if (p >= first)
                p = first + (p - first) % period;
            qs[i][0] = i;
            qs[i][1] = r;
            qs[i][2] = c;
            qs[i][3] = (int) p;
        }
        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[3] - o2[3];
            }
        });

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                a0[i][j] = a[i][j];
        for (int I = 0, J = 0; I < hashes.size(); I++) {
            while (J < t && qs[J][3] == I) {
                qs[J][4] = a0[qs[J][1]][qs[J][2]];
                J++;
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    boolean is = false;
                    for (int[] dir : dirs) {
                        int i1 = i + dir[0];
                        int j1 = j + dir[1];
                        if (i1 >= 0 && i1 < n && j1 >= 0 && j1 < m) {
                            if (a0[i][j] == a0[i1][j1]) {
                                is = true;
                                break;
                            }
                        }
                    }
                    if (is)
                        a1[i][j] = (char) ('0' + '1' - a0[i][j]);
                    else
                        a1[i][j] = a0[i][j];
                }
            }
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    a0[i][j] = a1[i][j];

        }

        Arrays.sort(qs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        for (int i = 0; i < t; i++)
            out.println((char) qs[i][4]);
    }

    public static void main(String[] args) throws FileNotFoundException {
        in = new FastReader(System.in);
//        in = new FastReader(new FileInputStream("sometext.txt"));
        out = new PrintWriter(System.out);
//        out = new PrintWriter(new FileOutputStream("output.txt"));

        solve();

//        Thread thread = new Thread(null, () -> {
//            solve();
//        });
//        thread.start();
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        out.flush();
        out.close();
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        FastReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        Integer nextInt() {
            return Integer.parseInt(next());
        }

        Long nextLong() {
            return Long.parseLong(next());
        }

        Double nextDouble() {
            return Double.parseDouble(next());
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine());
            }
            return st.nextToken();
        }

        String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
    }
}