原题描述:https://leetcode-cn.com/problems/surrounded-regions/description/
给定一个二维的矩阵,包含 'X'
和 'O'
(字母 O)。
找到所有被 'X'
围绕的区域,并将这些区域里所有的 'O'
用 'X'
填充。
示例:
X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:
X X X X
X X X X
X X X X
X O X X
解释:
被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O'
都不会被填充为 'X'
。 任何不在边界上,或不与边界上的 'O'
相连的 'O'
最终都会被填充为 'X'
。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
遗憾的是最后一个用例没有通过!
class Solution {
public:
int NN=1000;
int res[1000][1000]= {
0
};
vector<int> checked;
set<int> quanquan;
void solve(vector<vector<char>>& board) {
int N=board.size();
if(N==0) return;
int M=board[0].size();
cout<<M<<" "<<N<<endl;
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
res[i][j]=0;
if(board[i][j]=='X') res[i][j]=1;
if(board[i][j]=='O'&&(i==0||j==0||i==N-1||j==M-1) )
res[i][j]=-1;
}
}
int count=0;
bool out=false;
do {
count=0;
out=false;
quanquan.clear();
checked.clear();
for(int i=1; i<N-1; i++) {
for(int j=1; j<M-1; j++) {
if(res[i][j]==0) {
//cout<<i<<" ---"<<N<<" "<<j<<endl;
count++;
dfs(i,j,board);
bool c=true;
for(int k=0; k<checked.size(); k++) {
int ss=checked[k];
if(res[ss/NN][ss%NN]==-1) {
c=false;
break;
}
}
set<int>::iterator it=quanquan.begin();
for(int k=0; k<quanquan.size(); k++) {
int ss=*(it);
it++;
if(c) {
board[ss/NN][ss%NN]='X';
res[ss/NN][ss%NN]=1;
} else {
board[ss/NN][ss%NN]='O';
res[ss/NN][ss%NN]=-1;
}
}
out=true;
break;
}
}
if(out) break;
}
} while(count) ;
}
bool dfs(int i,int j,vector<vector<char>>& board) { //除了flag方法,其余方向是ok
//left 1,right 2,up3 down 4
int ss;
ss=i*NN+j;
quanquan.insert(ss);
// left
ss=i*NN+j-1;
//cout<<res[i][j-1]<<endl; cout <<res[i][j+1]<<endl; cout<<res[i-1][j]<<endl; cout<<res[i+1][j]<<endl;
if(res[i][j-1]) {
checked.push_back(ss);
} else {
if(!quanquan.count(ss))
dfs(i,j-1,board);
}
//right
ss=i*NN+j+1;
if(res[i][j+1]) {
checked.push_back(ss);
} else {
if(!quanquan.count(ss))
dfs(i,j+1,board);
}
//up
ss=(i-1)*NN+j;
if(res[i-1][j]) {
checked.push_back(ss);
} else {
if(!quanquan.count(ss))
dfs(i-1,j,board);
}
//down
ss=(i+1)*NN+j;
if(res[i+1][j]) {
checked.push_back(ss);
} else {
if(!quanquan.count(ss))
dfs(i+1,j,board);
}
return true;
}
};
网上优秀代码
class Solution {
int dep,wid;
char[][]map;
public void dsf(int depth, int width) {
if(depth<0||depth>=dep||width<0||width>=wid||map[depth][width]!='O')return;
map[depth][width]='Q';
dsf(depth-1,width);
dsf(depth+1,width);
dsf(depth,width-1);
dsf(depth,width+1);
}
public void solve(char[][] board) {
map=board;
dep=board.length;
if(dep==0)return;
wid=board[0].length;
for(int i=0;i<dep;i++){
if(map[i][0]=='O')dsf(i,0);
if(map[i][wid-1]=='O')dsf(i,wid-1);
}
for (int i=0;i<wid;i++){
if(map[0][i]=='O')dsf(0,i);
if(map[dep-1][i]=='O')dsf(dep-1,i);
}
for (int i=0;i<dep;i++)
for (int j=0;j<wid;j++){
if(map[i][j]=='O')map[i][j]='X';
else if(map[i][j]=='Q')map[i][j]='O';
}
}
}