# 【題解】Codeforces 1350E. Orac and Game of Life

```#include <iostream>
#include <queue>
using namespace std;

int n, m, t, d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int g[1005][1005], r[1005][1005], a, b;
long long c;
string s;
queue <pair<int, int>> q;

int main() {
cin >> n >> m >> t;
for (int i = 0; i < n; i++){
cin >> s;
for (int j = 0; j < m; j++){
g[i][j] = s[j]-'0';
r[i][j] = -1;
}
}
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
for (int k = 0; k < 4; k++){
if (0 <= i+d[k][0] && i+d[k][0] < n && 0 <= j+d[k][1] && j+d[k][1] < m && g[i+d[k][0]][j+d[k][1]] == g[i][j]){
q.push({i, j});
r[i][j] = 0;
break;
}
}
}
}
while (!q.empty()){
pair<int, int> p = q.front();
q.pop();
for (int k = 0; k < 4; k++){
if (0 <= p.first+d[k][0] && p.first+d[k][0] < n && 0 <= p.second+d[k][1] && p.second+d[k][1] < m){
if (r[p.first+d[k][0]][p.second+d[k][1]] == -1){
r[p.first+d[k][0]][p.second+d[k][1]] = r[p.first][p.second]+1;
q.push({p.first+d[k][0], p.second+d[k][1]});
}
}
}
}
for (int i = 0; i < t; i++){
cin >> a >> b >> c;
a--;
b--;
if (c <= r[a][b] || r[a][b] == -1) cout << g[a][b] << "\n";
else{
c -= r[a][b];
c %= 2;
if (c) cout << (g[a][b]^1) << "\n";
else cout << g[a][b] << "\n";
}
}
}
```