LC-130 被环绕区域

问题:

输入一个矩阵,将被X字符包围的O字符全部替换为X,但是如果某个O字符处于矩阵的边界,则该O字符及其连接的所有O字符都不变。

输出替换后的矩阵。

 

 

思路:

先遍历矩阵每一个字符,当发现O字符,则利用深搜方式找出与之相连的所有O字符。

每找出一个O字符,则先将其改为X字符,并将相连接的四个方向的O字符的坐标存入search栈中。并且将这个替换后的字符的坐标,保存在recover栈中。

在搜索相连接的O字符时,如果发现所连接的是边界字符,则说明这次找到的O字符区域,是不需要改变的,但是因为我们之前都改为X了(为了避免重复搜索字符),所以最后的时候,将找到的这部分字符区域,重新标记为F字符。

最后在检索完所有字符区域后,就将F字符恢复为O字符。

 

代码:

 1 class Solution {
 2 public:
 3     void solve(vector<vector<char>>& board) {
 4         if (board.size() == 0) return;
 5         rows = board.size();
 6         cols = board[0].size();
 7         for (int i = 0; i < rows; i++) {
 8             for (int j = 0; j < cols; j++) {
 9                 if (i > 0 && i < rows - 1 && j > 0 && j < cols - 1 && board[i][j] == 'O') {
10                     searchAndRecover(board, i, j);
11                 }
12             }
13         }
14         for (int i = 0; i < rows; i++) {
15             for (int j = 0; j < cols; j++) {
16                 if (board[i][j] == 'F') {
17                     board[i][j] = 'O';
18                 }
19             }
20         }
21     }
22     void searchAndRecover(vector<vector<char>>& board, int x, int y) {
23         // intialize
24         searching.clear();
25         recover.clear();
26         int directions[4][2] = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};
27         bool need_recovery = false;
28         // store the original one
29         pair<int, int> origin(x, y);
30         searching.push_back(origin);
31         while (!searching.empty()) {
32             // get the top of the stack
33             pair<int, int> tmp = searching.back();
34             searching.pop_back();
35             // change the value
36             board[tmp.first][tmp.second] = 'X';
37             recover.push_back(tmp);
38             for (int i = 0; i < 4; i++) {
39                 int tmp_x = tmp.first + directions[i][0];
40                 int tmp_y = tmp.second + directions[i][1];
41                 if (tmp_x >= 0 && tmp_x < rows && tmp_y >= 0 && tmp_y < cols && board[tmp_x][tmp_y] == 'O') {
42                     if (tmp_x > 0 && tmp_x < rows - 1 && tmp_y > 0 && tmp_y < cols - 1) {
43                         pair<int, int> add_point(tmp_x, tmp_y);
44                         searching.push_back(add_point);
45                     }
46                     else {
47                         need_recovery = true;
48                     }
49                 }
50             }
51         }
52         if (need_recovery) {
53             while (!recover.empty()) {
54                 pair<int, int> tmp = recover.back();
55                 board[tmp.first][tmp.second] = 'F';
56                 recover.pop_back();
57             }
58         }
59     }
60 private:
61     int rows;
62     int cols;
63     vector<pair<int, int>> searching;
64     vector<pair<int, int>> recover;
65 };

 

posted @ 2019-09-18 13:46  leo_lee  阅读(267)  评论(0编辑  收藏  举报