1. const int INF = (1 << 30);

  2. const int NMAX = 1005;

  3. int N, M, T;

  4. char s[NMAX][NMAX];

  5. bool bad[NMAX][NMAX];

  6. bool seen[NMAX][NMAX];

  7. int dist[NMAX][NMAX];

  8. char color[NMAX][NMAX];

  9. int dx[] = {-1, 1, 0, 0};

  10. int dy[] = {0, 0, -1, 1};


  11. bool Inside(int i, int j)

  12. {

  13. return 1 <= i && i <= N && 1 <= j && j <= M;

  14. }


  15. int Fill(int startx, int starty, char val)

  16. {

  17. int cnt = 1;

  18. stack <pii> st;

  19. st.push(mp(startx, starty));

  20. seen[startx][starty] = true;

  21. while (!st.empty())

  22. {

  23. int i = st.top().first;

  24. int j = st.top().second;

  25. st.pop();

  26. for (int k = 0; k < 4; ++k)

  27. {

  28. int x = i + dx[k];

  29. int y = j + dy[k];

  30. if (Inside(x, y) && seen[x][y] == false && s[x][y] == val)

  31. {

  32. st.push(mp(x, y));

  33. seen[x][y] = true;

  34. ++cnt;

  35. }

  36. }

  37. }

  38. return cnt;

  39. }


  40. int main()

  41. {

  42. #ifndef ONLINE_JUDGE

  43. ifstream cin("test.in");

  44. #endif

  45. #ifdef ONLINE_JUDGE

  46. ios_base::sync_with_stdio(false);

  47. cin.tie(nullptr);

  48. #endif

  49. cin >> N >> M >> T;

  50. for (int i = 1; i <= N; ++i)

  51. cin >> (s[i] + 1);

  52. for (int i = 1; i <= N; ++i)

  53. for (int j = 1; j <= M; ++j)

  54. {

  55. if (seen[i][j] == false)

  56. if (Fill(i, j, s[i][j]) == 1)

  57. bad[i][j] = true;

  58. }

  59. queue <pair <pii ,char>> q;

  60. for (int i = 1;i <= N;++i)

  61. for (int j = 1; j <= M; ++j)

  62. {

  63. color[i][j] = s[i][j];

  64. if (bad[i][j])

  65. dist[i][j] = INF;

  66. else

  67. {

  68. dist[i][j] = 0;

  69. q.push(mp(mp(i, j), s[i][j]));

  70. }

  71. }

  72. while (!q.empty())

  73. {

  74. int i = q.front().first.first;

  75. int j = q.front().first.second;

  76. char from = q.front().second;

  77. q.pop();

  78. for (int k = 0; k < 4; ++k)

  79. {

  80. int x = i + dx[k];

  81. int y = j + dy[k];

  82. if (Inside(x, y) && dist[x][y] > dist[i][j] + 1)

  83. {

  84. color[x][y] = from;

  85. dist[x][y] = dist[i][j] + 1;

  86. q.push(mp(mp(x, y), from));

  87. }

  88. }

  89. }

  90. while (T-- > 0)

  91. {

  92. long long i, j, p;

  93. cin >> i >> j >> p;

  94. if (dist[i][j] == INF || p <= dist[i][j])

  95. cout << (s[i][j] - '0') << "\n";

  96. else

  97. {

  98. p -= dist[i][j];

  99. if (p % 2)

  100. cout << ('1' - s[i][j]) << "\n";

  101. else

  102. cout << (s[i][j] - '0') << "\n";

  103. }

  104. }

  105. #ifndef ONLINE_JUDGE

  106. cout << "\n\n\nTime elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";

  107. cin.close();

  108. #endif

  109. return 0;

  110. }