码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Surrounded Regions

时间:2014-06-28 18:03:06      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   art   

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)
下面提供深搜代码
bubuko.com,布布扣
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);
        }
    }
}

 

Leetcode Surrounded Regions,布布扣,bubuko.com

Leetcode Surrounded Regions

标签:style   blog   http   color   os   art   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3797135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!