leetcode[130]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
class Solution { public: void travel(int i, int j, vector<vector<char>> &board) { if(i<0||i>=board.size()||j<0||j>=board[0].size())return; if(board[i][j]=='O') { board[i][j]='Q'; if(i-1>=1)travel(i-1,j,board); if(i+1<=board.size()-2)travel(i+1,j,board); if(j-1>=1)travel(i,j-1,board); if(j+1<=board.size()-2)travel(i,j+1,board); } } void solve(vector<vector<char>> &board) { if(board.empty()||board.size()<3||board[0].size()<3)return; int m=board.size(); int n=board[0].size(); for(int i=0;i<m;i++) { if(board[i][0]=='O')travel(i,0,board); if(board[i][n-1]=='O')travel(i,n-1,board); } for(int j=0;j<n;j++) { if(board[0][j]=='O')travel(0,j,board); if(board[m-1][j]=='O')travel(m-1,j,board); } for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(board[i][j]=='X')continue; board[i][j]=board[i][j]=='Q'?'O':'X'; } } } };