题目地址:
Surrounded Regions | LeetCode OJ https://leetcode.com/problems/surrounded-regions/
此题可用DFS和BFS两种方法解:
解题思路:可以从二维矩阵的最外围开始搜索,所有外围O开始的连通区域O需要保存,所有和外围O不连通的区域O全部变为X;
DFS:
class Solution
{
public:
int dfs(int x,int y,int dirx[],int diry[],int lenx,int leny,vector>& board)
{
for(int i = 0; i< 4; i++)
{
int dxx = x+ dirx[i];
int dyy = y+ diry[i];
if(dxx < 0 || dxx >= lenx || dyy <0 || dyy >=leny)
{
continue;
}
if(board[dxx][dyy] == 'O')
{
board[dxx][dyy] = 'Q';
dfs(dxx,dyy,dirx,diry,lenx,leny,board);
}
}
return 0;
}
void solve(vector>& board)
{
int dirx[4] = {-1,1,0,0};
int diry[4] = {0,0,-1,1};
vector>::iterator itr0;
for(int i = 0; i < board.size();i++)
{
for(int j = 0 ; j < board[0].size();j++)
{
if(i== 0 || i == board.size()-1 || j == 0 || j == board[0].size()-1)
{
if(board[i][j] == 'O')
{
board[i][j] = 'Q';
dfs(i,j,dirx,diry,board.size()-1,board[0].size()-1,board);
}
}
}
}
for(int i = 0; i < board.size();i++)
{
for(int j = 0 ; j < board[0].size();j++)
{
if(board[i][j] == 'Q')
{
board[i][j] = 'O';
}
else if(board[i][j] == 'O')
{
board[i][j] = 'X';
}
}
}
}
};
BFS:
class Solution
{
public:
int dfs(int x,int y,int dirx[],int diry[],int lenx,int leny,vector>& board)
{
for(int i = 0; i< 4; i++)
{
int dxx = x+ dirx[i];
int dyy = y+ diry[i];
if(dxx < 0 || dxx >= lenx || dyy <0 || dyy >=leny)
{
continue;
}
if(board[dxx][dyy] == 'O')
{
board[dxx][dyy] = 'Q';
dfs(dxx,dyy,dirx,diry,lenx,leny,board);
}
}
return 0;
}
int bfs(int x,int y,int dirx[],int diry[],int lenx,int leny,vector>& board)
{
typedef struct
{
int x;
int y;
}NODE;
NODE queue[1000];
int head,rear;
head = 0;
rear = 0;
queue[rear].x = x;
queue[rear].y = y;
rear++;
while(head != rear)
{
NODE cur;
cur = queue[head];
for(int i = 0; i< 4; i++)
{
int dxx = cur.x+ dirx[i];
int dyy =cur.y+ diry[i];
if(dxx < 0 || dxx >= lenx || dyy <0 || dyy >=leny)
{
continue;
}
if(board[dxx][dyy] == 'O')
{
board[dxx][dyy] = 'Q';
queue[rear].x = dxx;
queue[rear].y = dyy;
rear++;
}
}
head++;
}
return 0;
}
void solve(vector>& board)
{
int dirx[4] = {-1,1,0,0};
int diry[4] = {0,0,-1,1};
vector>::iterator itr0;
for(int i = 0; i < board.size();i++)
{
for(int j = 0 ; j < board[0].size();j++)
{
if(i== 0 || i == board.size()-1 || j == 0 || j == board[0].size()-1)
{
if(board[i][j] == 'O')
{
board[i][j] = 'Q';
bfs(i,j,dirx,diry,board.size()-1,board[0].size()-1,board);
}
}
}
}
for(int i = 0; i < board.size();i++)
{
for(int j = 0 ; j < board[0].size();j++)
{
if(board[i][j] == 'Q')
{
board[i][j] = 'O';
}
else if(board[i][j] == 'O')
{
board[i][j] = 'X';
}
}
}
}
};