fork download
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. using Point = std::pair<int, int>;
  5.  
  6. const int W = 5;
  7. const int H = 5;
  8.  
  9. bool m[W][H] = {{0, 0, 0, 1, 0},
  10. {0, 0, 0, 1, 0},
  11. {0, 0, 0, 1, 0},
  12. {0, 0, 0, 1, 0},
  13. {0, 0, 0, 1, 0}};
  14.  
  15. void fillUsingStack(bool m[W][H], int startX, int startY)
  16. {
  17. std::stack<Point> S;
  18. S.push({startX, startY});
  19.  
  20. while (!S.empty())
  21. {
  22. // get top element
  23. Point p = S.top();
  24. S.pop();
  25.  
  26. // check boundaries
  27. if (p.first < 0 || p.first >= W || p.second < 0 || p.second >= H)
  28. continue;
  29.  
  30. // skip when already colored
  31. if (m[p.first][p.second])
  32. continue;
  33.  
  34. // color current tile
  35. m[p.first][p.second] = 1;
  36.  
  37. // put all the neighbours on the stack
  38. S.push({p.first + 1, p.second});
  39. S.push({p.first - 1, p.second});
  40. S.push({p.first, p.second + 1});
  41. S.push({p.first, p.second - 1});
  42. }
  43. }
  44.  
  45. void printMap(bool m[W][H])
  46. {
  47. for (int y = 0; y < H; ++y)
  48. {
  49. for (int x = 0; x < W; ++x)
  50. std::cout << m[x][y] ? "1 " : "0 ";
  51. std::cout << "\n";
  52. }
  53. std::cout << std::endl;
  54. }
  55.  
  56. int main() {
  57. printMap(m);
  58.  
  59. fillUsingStack(m, 2, 2);
  60.  
  61. printMap(m);
  62. return 0;
  63. }
Success #stdin #stdout 0s 4264KB
stdin
Standard input is empty
stdout
00000
00000
00000
11111
00000

11111
11111
11111
11111
00000