代码改变世界

Surrounded Regions

2015-04-10 19:55  笨笨的老兔子  阅读(131)  评论(0编辑  收藏  举报

给定一个由字符'X'和‘O’组成的矩阵,消除所有被‘X’包围的‘O’

X X X X
X O O X
X X O X
X O X X
变成
X X X X
X X X X
X X X X
X O X X
思路:有点像围棋里一块区域是否有气,只有有气的才能存活下来。即只有‘O’到达了四条边界才可以存活,因此从四条边界开始做广搜,将所有搜索到的'O'赋值为‘1’,然后遍历整个矩阵将所有之前没有被赋值的‘O’赋值为‘X’,将‘1’还原为‘O’即可。

  1. class Solution {
  2. public:
  3. void solve(vector<vector<char>> &board) {
  4. if (board.empty())
  5. return;
  6. int width = board[0].size();
  7. int height = board.size();
  8. for (size_t i = 0; i < width; i++)
  9. {
  10. if (board[0][i] == 'O')
  11. bfs(0, i, board);
  12. if (board[height - 1][i] == 'O')
  13. bfs(height-1, i, board);
  14. }
  15. for (size_t i = 0; i < height; i++)
  16. {
  17. if (board[i][0] == 'O')
  18. bfs(i, 0, board);
  19. if (board[i][width - 1] == 'O')
  20. bfs(i, width - 1, board);
  21. }
  22. for (size_t i = 0; i < height; i++)
  23. {
  24. for (size_t j = 0; j < width; j++)
  25. {
  26. if (board[i][j] == '1')
  27. board[i][j] = 'O';
  28. else if (board[i][j] == 'O')
  29. {
  30. board[i][j] = 'X';
  31. }
  32. }
  33. }
  34. }
  35. void bfs(int x,int y, vector<vector<char> >&board)
  36. {
  37. board[x][y] = '1';
  38. queue<Point> qPoint;
  39. qPoint.push(Point(x,y));
  40. Point tmpPoint=Point(0,0);
  41. int xBound = board.size();
  42. int yBound = board[0].size();
  43. while (!qPoint.empty())
  44. {
  45. tmpPoint = qPoint.front();
  46. x = tmpPoint.x;
  47. y = tmpPoint.y;
  48. if (isInside(x+1, y, xBound, yBound) && board[x+1][y] == 'O')
  49. {
  50. qPoint.push(Point(x+1, y));
  51. board[x+1][y] = '1';
  52. }
  53. if (isInside(x-1, y, xBound, yBound) && board[x-1][y] == 'O')
  54. {
  55. qPoint.push(Point(x-1, y));
  56. board[x-1][y] = '1';
  57. }
  58. if (isInside(x, y+1, xBound, yBound) && board[x][y+1] == 'O')
  59. {
  60. qPoint.push(Point(x, y+1));
  61. board[x][y+1] = '1';
  62. }
  63. if (isInside(x, y - 1, xBound, yBound) && board[x][y - 1] == 'O')
  64. {
  65. qPoint.push(Point(x, y - 1));
  66. board[x][y - 1] = '1';
  67. }
  68. qPoint.pop();
  69. }
  70. }
  71. bool isInside(int x, int y, int xBound, int yBound)
  72. {
  73. return x >= 0 && x < xBound && y >= 0 && y < yBound;
  74. }
  75. struct Point
  76. {
  77. int x;
  78. int y;
  79. Point(int a, int b) :x(a), y(b){}
  80. };
  81. };