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 O2M(vector<vector<char> >&board, int i, int j){
//从board[i][j]开始,遍历'O'区域,把'O'替换成'M'
int rows=board.size();
int cols=board[0].size();
queue<int> qe;
qe.push(i*cols+j);
board[i][j]='M';
while(!qe.empty()){
int pos = qe.front(); qe.pop();
i=pos/cols;
j=pos%cols;
//判断上方
if(i-1>=0 && board[i-1][j]=='O'){
board[i-1][j]='M'; //注意在将相邻元素填到队列中时,需要将它标记为以访问,否则以后在确定其他节点的'O'相邻位置时,很有可能又把这个节点加入到队列中。造成死循环。
qe.push((i-1)*cols + j);
}
//判断下方
if(i+1<rows && board[i+1][j]=='O'){
board[i+1][j]='M';
qe.push((i+1)*cols + j);
}
//判断左方
if(j-1>=0 && board[i][j-1]=='O'){
board[i][j-1]='M';
qe.push(i*cols + j-1);
}
//判断右方
if(j+1<cols && board[i][j+1]=='O'){
board[i][j+1]='M';
qe.push(i*cols + j+1);
}
}
}
void solve(vector<vector<char>> &board) {
int rows=board.size();
if(rows==0)return;
int cols=board[0].size();
if(cols==0)return;
//把临边的'O'区域替换成'M'
//上边
for(int j=0; j<cols; j++){
if(board[0][j]=='O')O2M(board, 0, j);
}
//下边
for(int j=0; j<cols; j++){
if(board[rows-1][j]=='O')O2M(board, rows-1, j);
}
//左边
for(int i=0; i<rows; i++){
if(board[i][0]=='O')O2M(board, i, 0);
}
//右边
for(int i=0; i<rows; i++){
if(board[i][cols-1]=='O')O2M(board, i, cols-1);
}
//扫描矩阵,把O替换成X, 把M替换成O
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(board[i][j]=='O')board[i][j]='X';
else if(board[i][j]=='M')board[i][j]='O';
}
}
}
};LeetCode: Surrounded Regions [130],布布扣,bubuko.com
LeetCode: Surrounded Regions [130]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/34127147