LeetCode | 130. Surrounded Regions

 

题目:

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.

 

代码:

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if(board.size() < 1)
            return;
        int h = board.size();
        int w = board[0].size();
        if(w < 1)
            return;
        
        vector<vector<int>> record(h, vector<int>(w, 0));
        vector<vector<int>> mboard(h, vector<int>(w, 0));
        
        queue<pair<int, int>> q;
        for(int i = 0; i<h; i++)
        {
            for(int j = 0; j<w; j++)
            {
                if(i == 0 || i == h - 1 || j == 0 || j == w - 1)
                {
                    if(board[i][j] == 'O' && !record[i][j])
                    {
                        q.push(pair<int, int>(i, j));
                        mboard[i][j] = 1;
                    }
                    record[i][j] = 1;
                }
            }
        }
        
        vector<vector<int>> d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while(!q.empty())
        {
            pair<int, int> cur = q.front();
            q.pop();
            pair<int, int> pos;
            for(int k = 0; k < 4; k++)
            {
                pos.first = cur.first + d[k][0];
                pos.second = cur.second + d[k][1];
                if(pos.first < 0 || pos.first >= h || pos.second < 0 || pos.second >= w)
                    continue;
                
                if(board[pos.first][pos.second] == 'O' && !record[pos.first][pos.second])
                {
                    mboard[pos.first][pos.second] = 1;
                    q.push(pos);
                }
                
                record[pos.first][pos.second] = 1;
            }
        }
        
        for(int i = 0; i<h; i++)
        {
            for(int j = 0; j<w; j++)
            {
                if(mboard[i][j] == 1)
                    continue;
                board[i][j] = 'X';
            }
        }
        return;
    }
};




一次AC,虽然效率不太高~

 

题外话:

转眼就到了七月底。七月,算是一年中最喜欢的一个月,这次走的好匆忙。

可能,有持续工作的疲倦,多个项目交叉更迭的应接不暇,时间管理的懈怠。

但也有值得开心的事情,虽然焦灼但都在稳步推进着,Taylor发了folklore,安静统一的一张专辑,很耐听很治愈。

希望这个周末彻底放松一下吧!然后好好计划接下来的事情~ 适当的做减法,加强注意力利用率。

Anyway, hope for the best.

七月,再见。

你好,八月。

 

 

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页