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.

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

思路

本题依旧是union-find题目,这个就比较简单了,

  • 首先检查矩阵四周是否存在‘O’,如果存在则将‘O’及其相邻‘O’转成‘1’
  • 遍历矩阵将‘O’转成‘X’,将‘1’转成‘O’
     X X X X           X X X X             X X X X
     X X O X  ->       X X O X    ->       X X X X
     X O X X           X 1 X X             X O X X
     X O X X           X 1 X X             X O X X

代码

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int i,j;
        int row=board.size();
        if(!row)
            return;
        int col=board[0].size();
//检查矩阵四周的值
        for(i=0;i0,row,col);
            if(col>1)
                check(board,i,col-1,row,col);
        }
        for(j=1;j+10,j,row,col);
            if(row>1)
                check(board,row-1,j,row,col);
        }
        //将'O'转成'X'
        for(i=0;ifor(j=0;jif(board[i][j]=='O')
                    board[i][j]='X';
        //将'1'转成'O'
        for(i=0;ifor(j=0;jif(board[i][j]=='1')
                    board[i][j]='O';
    }
    //检查矩阵,如果四个边有'O'那么将'O'及其相邻的'O'置为'1'
    void check(vector<vector<char> >&vec,int i,int j,int row,int col){
        if(vec[i][j]=='O'){
            vec[i][j]='1';
            if(i>1)
                check(vec,i-1,j,row,col);
            if(j>1)
                check(vec,i,j-1,row,col);
            if(i+11,j,row,col);
            if(j+11,row,col);
        }
    }
};

你可能感兴趣的:(Leetcode,基础算法)