Surrounded Regions

描述

Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region .

For example,

  1. X X X X
  2. X O O X
  3. X X O X
  4. X O X X

After running your function, the board should be:

  1. X X X X
  2. X X X X
  3. X X X X
  4. X O X X

分析

广搜。从上下左右四个边界往里走,凡是能碰到的'O',都是跟边界接壤的,应该保留。

代码

  1. // LeetCode, Surrounded Regions
  2. // BFS,时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. void solve(vector<vector<char>> &board) {
  6. if (board.empty()) return;
  7. const int m = board.size();
  8. const int n = board[0].size();
  9. for (int i = 0; i < n; i++) {
  10. bfs(board, 0, i);
  11. bfs(board, m - 1, i);
  12. }
  13. for (int j = 1; j < m - 1; j++) {
  14. bfs(board, j, 0);
  15. bfs(board, j, n - 1);
  16. }
  17. for (int i = 0; i < m; i++)
  18. for (int j = 0; j < n; j++)
  19. if (board[i][j] == 'O')
  20. board[i][j] = 'X';
  21. else if (board[i][j] == '+')
  22. board[i][j] = 'O';
  23. }
  24. private:
  25. void bfs(vector<vector<char>> &board, int i, int j) {
  26. typedef pair<int, int> state_t;
  27. queue<state_t> q;
  28. const int m = board.size();
  29. const int n = board[0].size();
  30. auto state_is_valid = [&](const state_t &s) {
  31. const int x = s.first;
  32. const int y = s.second;
  33. if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O')
  34. return false;
  35. return true;
  36. };
  37. auto state_extend = [&](const state_t &s) {
  38. vector<state_t> result;
  39. const int x = s.first;
  40. const int y = s.second;
  41. // 上下左右
  42. const state_t new_states[4] = {{x-1,y}, {x+1,y},
  43. {x,y-1}, {x,y+1}};
  44. for (int k = 0; k < 4; ++k) {
  45. if (state_is_valid(new_states[k])) {
  46. // 既有标记功能又有去重功能
  47. board[new_states[k].first][new_states[k].second] = '+';
  48. result.push_back(new_states[k]);
  49. }
  50. }
  51. return result;
  52. };
  53. state_t start = { i, j };
  54. if (state_is_valid(start)) {
  55. board[i][j] = '+';
  56. q.push(start);
  57. }
  58. while (!q.empty()) {
  59. auto cur = q.front();
  60. q.pop();
  61. auto new_states = state_extend(cur);
  62. for (auto s : new_states) q.push(s);
  63. }
  64. }
  65. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/bfs/surrounded-regions.html