Surrounded Regions 分类: Leetcode(广度优先搜索...

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连通的路径,标记为'E',所有非E的都为X


class Solution {
public:
    int m ,n;
    void solve(vector> &board) {
        if (board.size() == 0) return;
        
        m = board.size();
        n = board[0].size();
        
        for (int i = 0; i < n; i++) {
            bfs(board, 0 , i);
            bfs(board, m-1, i);
        }
        
        for (int j = 1; j < m-1; j++) {
            bfs(board, j, 0);
            bfs(board, j, n-1);
        }
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j > &board, int i, int j) {
        queue q;
        visit(board,i,j,q);
        while(!q.empty()) {
            int cur = q.front();
            q.pop();
            const int x = cur/n;
            const int y = cur%n;
            visit(board, x-1, y, q);
            visit(board, x, y-1, q);
            visit(board, x+1, y, q);
            visit(board, x, y+1, q);
        }
    }
    
    void visit(vector> &board, int i, int j, queue &q) {
        if(i < 0 || i > m-1 || j <0 || j > n-1 || board[i][j] != 'O')
            return;
        board[i][j] = 'E';
        q.push(i*n+j);
    }
    
};






版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/learnordie/p/4656929.html

你可能感兴趣的:(数据结构与算法)