Leetcode Surrounded Regions

OpenSoucre發表於2014-06-19

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

題目不難理解,就是把被X包圍的O變成X,從題目給出的例子可以看出,只有在邊界有O的地方,才不會被X包圍,
故將起始搜尋位置縮小為邊界,常用的搜尋方法為深搜和廣搜
最開始題目採用深搜去解決發現題目ac不了,深搜的最大深度可能為n*m,但空間複雜度為O(1)
下面提供深搜程式碼
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};

class Solution {
public:
typedef vector<vector<char> > Board;
void dfs(int x, int y, Board& board){
    if(x < 0 || x >= board.size() || y < 0 || y >=board[0].size() || board[x][y]!='O') return;
    board[x][y] = 'Y';
    for(int i = 0 ; i < 4; ++ i){
        dfs(x+dx[i],y+dy[i],board);
    }
}

void solve(vector<vector<char> > &board){
    if(board.size() == 0) return;
    int n = board.size(),m = board[0].size();
    for(int i = 0 ; i < n; ++ i){
        dfs(i,0,board);
        dfs(i,m-1,board);
    }
    for(int j = 0; j < m; ++ j){
        dfs(0,j,board);
        dfs(n-1,j,board);
        
    }
    for(int  i = 0 ; i < n ; ++ i){
        for(int j = 0 ; j < m ; ++ j){
            board[i][j]=(board[i][j]=='Y'?'O':'X');
        }
    }
}
View Code

故本題用廣搜去解決,廣搜的最大深度為max(n,m),但要開闢一個queue,故其空間複雜度為O(max(n,m))

 
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};

typedef pair<int,int> Point;
typedef vector<vector<char> > Board;

queue<Point> que;

void bfs(Board& board){
    while(!que.empty()){
        Point p = que.front();que.pop();
        board[p.first][p.second]='Y';
        for(int i = 0 ; i < 4; ++ i){
            int newX = x+dx, newY = y+dy;
            if(newX>=0 && newX<board.size() && newY>=0 && newY< board.size() && board[newX][newY]=='O' ) 
                que.push(Point(newX,newY));
        }
    }
}

void solve(vector<vector<char> >& board){
    if(board.size() == 0) return;
    int n = board.size(),m = board[0].size();

    for(int i = 0 ; i < n; ++ i){
        if(board[i][0] == 'O') que.push(Point(i,0));
        if(board[i][m-1] == 'O') que.push(Point(i,m-1));
    }
    bfs(board);
    for(int j = 0; j < m; ++ j){
        if(board[0][j] == 'O') que.push(Point(0,j));
        if(board[n-1][j] == 'O') que.push(Point(n-1,j));
    }
    bfs(board);
    for(int  i = 0 ; i < n ; ++ i){
        for(int j = 0 ; j < m ; ++ j){
            board[i][j]=(board[i][j]=='Y'?'O':'X');
        }
    }
}

 

相關文章