Leetcode 130. Surrounded Regions

题目

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

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

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

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.


Solution

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int n = board.size();
        if (n == 0) return;
        int m = board[0].size();
        vector<vector<bool>> visited(n, vector<bool>(m, false));
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                vector<pair<int, int>> os;
                bool tag = true;
                if (!visited[i][j] && board[i][j] == 'O') {
                    queue<pair<int,int>> q;
                    q.push(make_pair(i, j));
                    while (!q.empty()) {
                        auto p = q.front();
                        int x = p.first, y = p.second;
                        if (x == 0 || y == 0 || x == n-1 || y == m-1) {
                           tag = false; 
                        }
                        os.push_back(p);
                        if (x > 0 && !visited[x-1][y] && board[x-1][y] == 'O') {
                            visited[x-1][y] = true;
                            q.push(make_pair(x-1, y));
                        } 
                        if (x < n-1 && !visited[x+1][y] && board[x+1][y] == 'O') {
                            visited[x+1][y] = true;
                            q.push(make_pair(x+1, y));
                        } 
                        if (y > 0 && !visited[x][y-1] && board[x][y-1] == 'O') {
                            visited[x][y-1] = true;
                            q.push(make_pair(x, y-1));
                        } 
                        if (y < m-1 && !visited[x][y+1] && board[x][y+1] == 'O') {
                            visited[x][y+1] = true;
                            q.push(make_pair(x, y+1));
                        }
                        q.pop();
                    }                    
                }
                if (tag) {
                    for (int i = 0; i < os.size(); i++) {
                        board[os[i].first][os[i].second] = 'X';
                    }
                }
            }
        }
        
    }
};

题解

和博客的上一道题一样,也是寻找一个的操作。因此我们选择使用BFS(DFS当然也可以):

  1. 从每个节点出发,获取从这个节点出发且连通的所有所有节点(作为一个集合S);
  2. 检查S,如果其中有边界点,那么丢弃这个集合;如果没有,那么把这个集合都设置为X

分析

对于每个节点都只访问一次,因此复杂度为O(n)。

你可能感兴趣的:(Leetcode,C++技术博客)