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连通的所有O均不用转化成X(这里连通的意思是从边缘的O开始有一条全是O的路径可以到达该点),其他的所有O都变成X。我们只要从边缘的O开始dfs标记所有与它连通的O,然后再把所有未标记的O变成X。
下面的代码中是使用了一个标记数组。如果想节省空间,可以先把与边缘O连通的O先变成#,然后再把剩余的O变为X,再把#变成O。 本文地址
1 2 class Solution { 3 public: 4 struct Qnode 5 { 6 int i_; 7 int j_; 8 Qnode(int x,int y):i_(x),j_(y){}; 9 Qnode(){}; 10 }; 11 void solve(vector<vector<char>> &board) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 int row = board.size(); 15 if(row == 0)return; 16 int colum = board[0].size(); 17 queue<Qnode> myqueue; 18 bool visited[row][colum]; 19 memset(visited, 0, sizeof(visited)); 20 //首先标记所有没有被包围的O 21 for(int i = 0; i < row; i++) 22 { 23 for(int j = 0; j < colum; j++) 24 {//首先找到四周的O,和这个O连成一片的O都不用转换 25 if(i == 0 || i == row - 1 || j == 0 || j == colum - 1) 26 if(visited[i][j] == false && board[i][j] == 'O') 27 { 28 visited[i][j] = true; 29 myqueue.push(Qnode(i,j)); 30 while(myqueue.empty() == false) 31 { 32 Qnode tmp = myqueue.front(); 33 myqueue.pop(); 34 //board[tmp.i_][tmp.j_] = 'X'; 35 if(tmp.i_-1>=0 && board[tmp.i_-1][tmp.j_] == 'O' 36 &&visited[tmp.i_-1][tmp.j_] == false) 37 {//上 38 visited[tmp.i_-1][tmp.j_] = true; 39 myqueue.push(Qnode(tmp.i_-1, tmp.j_)); 40 } 41 if(tmp.i_+1 < row && board[tmp.i_+1][tmp.j_] == 'O' 42 &&visited[tmp.i_+1][tmp.j_] == false) 43 {//下 44 visited[tmp.i_+1][tmp.j_] = true; 45 myqueue.push(Qnode(tmp.i_+1, tmp.j_)); 46 } 47 if(tmp.j_-1 >= 0 && board[tmp.i_][tmp.j_-1] == 'O' 48 &&visited[tmp.i_][tmp.j_-1] == false) 49 {//左 50 visited[tmp.i_][tmp.j_-1] = true; 51 myqueue.push(Qnode(tmp.i_, tmp.j_-1)); 52 } 53 if(tmp.j_+1 < colum && board[tmp.i_][tmp.j_+1] == 'O' 54 &&visited[tmp.i_][tmp.j_+1] == false) 55 {//右 56 visited[tmp.i_][tmp.j_+1] = true; 57 myqueue.push(Qnode(tmp.i_, tmp.j_+1)); 58 } 59 } 60 } 61 } 62 } 63 //把未被标记的O转换成X 64 for(int i = 0; i < row; i++) 65 for(int j = 0; j < colum; j++) 66 if(board[i][j] == 'O' && visited[i][j] == false) 67 board[i][j] = 'X'; 68 69 } 70 };
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3421549.html