首页 > 其他 > 详细

LeetCode-130-Surrounded Regions

时间:2019-02-05 21:55:11      阅读:169      评论:0      收藏:0      [点我收藏+]

算法描述:

Given a 2D board containing ‘X‘ and ‘O‘ (the letter O), capture all regions surrounded by ‘X‘.

A region is captured by flipping all ‘O‘s into ‘X‘s in that surrounded region.

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

Explanation:

Surrounded regions shouldn’t be on the border, which means that any ‘O‘ on the border of the board are not flipped to ‘X‘. Any ‘O‘ that is not on the border and it is not connected to an ‘O‘ on the border will be flipped to ‘X‘. Two cells are connected if they are adjacent cells connected horizontally or vertically.

解题思路:深度优先搜索或者广度优先搜索。从边界开始搜索,将符合条件的值得索引放入队列中,并用额外的矩阵标记访符合要求的数值位置。

 void solve(vector<vector<char>>& board) {
        int m = board.size();
        if(m==0) return;
        int n = board[0].size();
        if(n==0) return;
        
        vector<vector<int>> alive(m, vector<int>(n, 0));
        queue<pair<int, int>> que;
        for(int i=0; i< m; i++){
            if(board[i][0] == O){
                alive[i][0] =1;
                que.push(make_pair(i,0));
            }
            if(board[i][n-1] == O){
                alive[i][n-1] =1;
                que.push(make_pair(i,n-1));
            }
        }
        
         for(int i=0; i< n; i++){
            if(board[0][i] == O){
                alive[0][i] =1;
                que.push(make_pair(0,i));
            }
            if(board[m-1][i] == O){
                alive[m-1][i] =1;
                que.push(make_pair(m-1,i));
            }
        }
        
        while(!que.empty()){
            pair<int,int> temp = que.front();
            que.pop();
            int dx[] = {-1,0,1,0};
            int dy[] = {0,1,0,-1};
            for(int i = 0; i < 4; i++){
                int ax = temp.first + dx[i];
                int ay = temp.second + dy[i];
                if(ax >= 0 && ay >=0 && ax < m && ay < n && alive[ax][ay] ==0 && board[ax][ay] == O){
                    alive[ax][ay] = 1;
                    que.push(make_pair(ax,ay));
                }
            }
        }
        for(int i=0; i < m; i++){
            for(int j=0; j <n; j++){
                if(alive[i][j]==0 && board[i][j]==O)
                    board[i][j] =X;
            }
        }
    }

 

LeetCode-130-Surrounded Regions

原文:https://www.cnblogs.com/nobodywang/p/10353164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!