标签:
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 { struct position { int x, y; position(int a, int b): x(a), y(b) {} }; public: void solve(vector<vector<char>>& board) { int row = board.size(); if(row <= 0) return; int col = board[0].size(); if(col <= 0) return; queue<position> q; int i, j; for(i = 0; i < col; i++) { if(‘O‘ == board[0][i]) q.push(position(0, i)); if(‘O‘ == board[row-1][i]) q.push(position(row-1, i)); } for(i = 0; i < row; i++) { if(‘O‘ == board[i][0]) q.push(position(i, 0)); if(‘O‘ == board[i][col-1]) q.push(position(i, col-1)); } while(!q.empty()) { position p = q.front(); q.pop(); board[p.x][p.y] = ‘N‘; if(p.x > 0 && ‘O‘ == board[(p.x)-1][p.y]) q.push(position((p.x)-1, p.y)); if(p.x < row-1 && ‘O‘ == board[(p.x)+1][p.y]) q.push(position((p.x)+1, p.y)); if(p.y > 0 && ‘O‘ == board[p.x][(p.y)-1]) q.push(position(p.x, (p.y)-1)); if(p.y < col-1 && ‘O‘ == board[p.x][(p.y)+1]) q.push(position(p.x, (p.y)+1)); } for(i = 0; i < row; i++) { for(j = 0; j < col; j++) { if(‘O‘ == board[i][j]) board[i][j] = ‘X‘; if(‘N‘ == board[i][j]) board[i][j] = ‘O‘; } cout<<endl; } } };
先找到四条边缘上面的字符,再找和这些字符相邻的字符。
130. Surrounded Regions -- 被某字符包围的区域
标签:
原文地址:http://www.cnblogs.com/argenbarbie/p/5470366.html