LeetCode[BFS]: Surrounded Regions,leetcodebfs

來源:互聯網
上載者:User

LeetCode[BFS]: Surrounded Regions,leetcodebfs

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

參考:https://oj.leetcode.com/discuss/9942/my-bfs-solution-c-28ms

採取逆向思維,不是找到所有被’X’包圍的’O’,而是將所有未被包圍的’O’先標記為’#’,然後將剩餘的’O’標記為’X’,將’#’標記為’O’,即可達到想要的目的。

C++代碼實現如下:

class Solution {public:    void solve(vector<vector<char>> &board) {        int height = board.size();        if (height == 0) return;        int width = board[0].size();        if (width == 0) return;        for (int i = 0; i < height; ++i) {            if (board[i][0] == 'O') BFSBoundary(board, i, 0);            if (board[i][width - 1] == 'O') BFSBoundary(board, i, width - 1);        }        for (int j = 1; j < width - 1; ++j) {            if (board[0][j] == 'O') BFSBoundary(board, 0, j);            if (board[height - 1][j] == 'O') BFSBoundary(board, height - 1, j);        }        for (int i = 0; i < height; ++i) {            for (int j = 0; j < width; ++j) {                if (board[i][j] == 'O') board[i][j] = 'X';                if (board[i][j] == '#') board[i][j] = 'O';            }        }    }private:    void BFSBoundary(vector<vector<char>> &board, int h, int w) {        int height = board.size();        int width = board[0].size();        queue<pair<int, int>> q;        q.push(make_pair(h, w));        board[h][w] = '#';        while (!q.empty()) {            pair<int, int> point = q.front();            q.pop();            pair<int, int> neighbors[4] = { { point.first + 1, point.second },                                            { point.first - 1, point.second },                                            { point.first, point.second + 1 },                                            { point.first, point.second - 1 } };            for (auto neig : neighbors) {                if ((neig.first >= 0 && neig.first < height)                    && (neig.second >= 0 && neig.second < width)                    && (board[neig.first][neig.second] == 'O')){                    q.push(make_pair(neig.first, neig.second));                    board[neig.first][neig.second] = '#';                }            }        }    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.