标签:
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
Breadth-first Search
#include <vector> #include <iostream> #include <iterator> using namespace std; class Solution { public: void solve(vector<vector<char> > &board) { int m=board.size(); if(m<2) return; int n=board[0].size(); if(n<2) return; vector<vector<bool> > flag; for(int i=0;i<m;i++) flag.push_back(vector<bool>(n,false)); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(board[i][j]==‘X‘) flag[i][j]=true; if(board[i][j]==‘O‘&&flag[i][j]==false) help_f(i,j,board,flag); } } return ; } void help_f(int i,int j,vector<vector<char> > &board,vector<vector<bool> > &flag) { // cout<<"Azhu"<<endl; vector<pair<int,int> > tmp; tmp.push_back({i,j}); flag[i][j]=true; int now_idx=0,m=board.size(),n=board[0].size(); while(now_idx<tmp.size()){ int now_i = tmp[now_idx].first,now_j = tmp[now_idx].second; if(now_i-1>=0&&board[now_i-1][now_j]==‘O‘&&flag[now_i-1][now_j]==false){ tmp.push_back({now_i-1,now_j}); flag[now_i-1][now_j]=true; } if(now_i+1<m&&board[now_i+1][now_j]==‘O‘&&flag[now_i+1][now_j]==false){ tmp.push_back({now_i+1,now_j}); flag[now_i+1][now_j]=true; } if(now_j-1>=0&&board[now_i][now_j-1]==‘O‘&&flag[now_i][now_j-1]==false){ tmp.push_back({now_i,now_j-1}); flag[now_i][now_j-1]=true; } if(now_j+1<n&&board[now_i][now_j+1]==‘O‘&&flag[now_i][now_j+1]==false){ tmp.push_back({now_i,now_j+1}); flag[now_i][now_j+1]=true; } now_idx++; } bool canCapture=true; now_idx=0; while(canCapture&&now_idx<tmp.size()){ int now_i = tmp[now_idx].first,now_j = tmp[now_idx].second; if(now_i==0||now_i==m-1||now_j==0||now_j==n-1) canCapture=false; now_idx++; } if(canCapture){ now_idx=0; while(now_idx<tmp.size()){ int now_i = tmp[now_idx].first,now_j = tmp[now_idx].second; board[now_i][now_j]=‘X‘; now_idx++; } } return ; } }; int main() { vector<vector<char> > board{ {{‘X‘,‘X‘,‘X‘,‘O‘}}, {{‘X‘,‘O‘,‘O‘,‘X‘}}, {{‘X‘,‘X‘,‘X‘,‘X‘}}, {{‘X‘,‘O‘,‘O‘,‘X‘}} }; Solution sol; sol.solve(board); for(int i=0;i<board.size();i++){ copy(board[i].begin(),board[i].end(),ostream_iterator<char>(cout," ")); cout<<endl; } return 0; }
[LeetCode] Surrounded Regions 广度搜索
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4204311.html