[LeetCode-130] Surrounded Regions
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,
X X X X X O O X X X O X X O X X
After running your function, the board should be:
X X X X X X X X X X X X X O X X
最边缘的O肯定要保留,然后以这些O为种子、把与它们毗邻的找出来,剩下的O全变成X就ok啦~
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 void solve(vector<vector<char>> &board) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int row_cnt = 0, col_cnt = 0; 7 if ((0 == (row_cnt = board.size())) || 8 (0 == (col_cnt = board.at(0).size()))) { 9 return; 10 } 11 12 union item_t { 13 struct { 14 int x; 15 int y; 16 }; 17 long long index; 18 }; 19 stack<item_t> keep_O; 20 item_t item, item_check; 21 22 #define CHECK_AND_PUSH_ITEM(IDX_X, IDX_Y, ITEM) \ 23 if ('O' == board.at((IDX_X)).at((IDX_Y))) { \ 24 ITEM.x = IDX_X; \ 25 ITEM.y = IDX_Y; \ 26 keep_O.push(ITEM); \ 27 board[IDX_X][IDX_Y] = 'T'; \ 28 } \ 29 30 // init stack 31 for (int i = 0; i < row_cnt; ++i) { 32 CHECK_AND_PUSH_ITEM(i, 0, item); 33 CHECK_AND_PUSH_ITEM(i, col_cnt - 1, item); 34 } 35 for (int i = 0; i < col_cnt; ++i) { 36 CHECK_AND_PUSH_ITEM(0, i, item); 37 CHECK_AND_PUSH_ITEM(row_cnt - 1, i, item); 38 } 39 40 while (!keep_O.empty()) { 41 item.index = keep_O.top().index; 42 keep_O.pop(); 43 if (item.x > 0) { 44 CHECK_AND_PUSH_ITEM(item.x - 1, item.y, item_check); 45 } 46 if (item.x < row_cnt - 1) { 47 CHECK_AND_PUSH_ITEM(item.x + 1, item.y, item_check) 48 } 49 if (item.y > 0) { 50 CHECK_AND_PUSH_ITEM(item.x, item.y - 1, item_check) 51 } 52 if (item.y < col_cnt - 1) { 53 CHECK_AND_PUSH_ITEM(item.x, item.y + 1, item_check) 54 } 55 } 56 57 // restruct 58 for (int i = 0; i < row_cnt; ++i) { 59 for (int j = 0; j < col_cnt; ++j) { 60 if ('T' == board.at(i).at(j)) { 61 board[i][j] = 'O'; 62 } 63 else if ('O' == board.at(i).at(j)) { 64 board[i][j] = 'X'; 65 } 66 } 67 } 68 } 69 };