130. Surrounded Regions

本文介绍了一种名为“包围区域”的算法问题,通过深度优先搜索(DFS)和广度优先搜索(BFS)两种方法实现解决方案。针对二维板上由‘X’字符包围的‘O’字符区域,将其转化为‘X’字符,而边缘相连的‘O’字符则保持不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:包围区域

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.

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’字符包围起来的区域就叫做一个区域被捕获。


思路一:

DFS解决。这道题有点像围棋,将包住的O都变成X,但不同的是边缘的O不算被包围,跟之前那道Number of Islands 岛屿的数量很类似,都可以用DFS来解。扫面矩阵的四条边,如果有O,则用DFS遍历,将所有连着的O都变成另一个字符。完成遍历,将剩下的‘O’都是被包围的,都变成‘X’字符,如果为‘$’字符的,说明是没有被包围住的,所以还原成‘O’字符。

代码:C++版:16ms

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        for (int i=0; i<board.size(); ++i) {
            for (int j=0; j<board[i].size(); ++j) {
                //核心控制,从二维板的四周开始向中心搜索,连在一起的‘O’字符都是没被包围的
                if ((i==0 || i==board.size()-1 || j==0 || j==board[i].size()-1) && board[i][j]=='O')
                    solveDFS(board, i, j);
            }
        }
        for (int i=0; i<board.size(); ++i) { //遍历结束,处理原二维板
            for (int j=0; j<board[i].size(); ++j) {
                if (board[i][j] == 'O') board[i][j] = 'X';
                if (board[i][j] == '$') board[i][j] = 'O';
            }
        }
    }
    void solveDFS(vector<vector<char>> &board, int i, int j) { //搜寻连在一起的‘O’字符
        if (board[i][j] == 'O') {
            board[i][j] = '$';
            if (i>0 && board[i-1][j] == 'O')
                solveDFS(board, i-1, j);
            if (j<board[i].size()-1 && board[i][j+1] == 'O')
                solveDFS(board, i, j+1);
            if (i<board.size()-1 && board[i+1][j] == 'O')
                solveDFS(board, i+1, j);
            if (j>1 && board[i][j-1] == 'O')
                solveDFS(board, i, j-1);
        }
    }
};
另一种写法,主要思路相同,只是DFS的递归实现方式不是太相同,使用了一些小技巧。

代码:C++版:92ms

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.empty() || board[0].empty()) return;
        int m = board.size(), n = board[0].size();
        for (int i=0; i<m; ++i) {
            for (int j=0; j<n; ++j) {
                if (i==0 || i==m-1 || j==0 || j==n-1) {
                    if (board[i][j] == 'O')
                        dfs(board, i, j);
                }
            }
        }
        for (int i=0; i<m; ++i) {
            for (int j=0; j<n; ++j) {
                if (board[i][j] == 'O') board[i][j] = 'X';
                if (board[i][j] == '$') board[i][j] = 'O';
            }
        }
    }
    void dfs(vector<vector<char>> &board, int x, int y) { //主要是这里的实现不一样
        int m = board.size(), n = board[0].size();
        vector<vector<int>> dir{{0, -1}, {-1,0}, {0,1}, {1,0}};
        board[x][y] = '$';
        for (int i=0; i<dir.size(); ++i) {
            int dx = x+dir[i][0], dy = y+dir[i][1];
            if (dx>=0 && dx<m && dy>0 && dy<n && board[dx][dy]=='O')
                dfs(board, dx, dy);
        }
    }
};

思路二:

BFS实现广搜。从上下左右四个边界往里走,凡是能碰到的'O',都是跟边界接壤的,应该保留。

代码:C++版:32ms

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.empty()) return;
        const int m = board.size();
        const int n = board[0].size();
        for (int i=0; i<n; i++) {
            bfs(board, 0, i);
            bfs(board, m-1, i);
        }
        for (int j=1; j<m-1; j++) {
            bfs(board, j, 0);
            bfs(board, j, n-1);
        }
        for (int i=0; i<m; i++) {
            for (int j=0; j<n; j++) {
                if (board[i][j] == 'O')
                    board[i][j] = 'X';
                else if (board[i][j] == '+')
                    board[i][j] = 'O';
            }
        }
    }
private:
    void bfs(vector<vector<char>> &board, int i, int j) {
        typedef pair<int, int> state_t;
        queue<state_t> q;
        const int m = board.size();
        const int n = board[0].size();
        
        auto is_valid = [&](const state_t &s) {
            const int x = s.first;
            const int y = s.second;
            if (x<0 || x>=m || y<0 || y>=n || board[x][y]!='O')
                return false;
            return true;
        };
        auto state_extend = [&](const state_t &s) {
            vector<state_t> res;
            const int x = s.first;
            const int y = s.second;
            //上下左右
            const state_t new_states[4] = {{x-1,y}, {x+1,y}, {x,y-1}, {x,y+1}};
            for (int k=0; k<4; ++k) {
                if (is_valid(new_states[k])) {
                    //既有标记功能又有去重功能
                    board[new_states[k].first][new_states[k].second] = '+';
                    res.push_back(new_states[k]);
                }
            }
            return res;
        };
        state_t start = {i,j};
        if (is_valid(start)) {
            board[i][j] = '+';
            q.push(start);
        }
        while (!q.empty()) {
            auto cur = q.front();
            q.pop();
            auto new_states = state_extend(cur);
            for (auto s : new_states)
                q.push(s);
        }
    }
};

### LeetCode Top 100 Popular Problems LeetCode provides an extensive collection of algorithmic challenges designed to help developers prepare for technical interviews and enhance their problem-solving skills. The platform categorizes these problems based on popularity, difficulty level, and frequency asked during tech interviews. The following list represents a curated selection of the most frequently practiced 100 problems from LeetCode: #### Array & String Manipulation 1. Two Sum[^2] 2. Add Two Numbers (Linked List)[^2] 3. Longest Substring Without Repeating Characters #### Dynamic Programming 4. Climbing Stairs 5. Coin Change 6. House Robber #### Depth-First Search (DFS) / Breadth-First Search (BFS) 7. Binary Tree Level Order Traversal[^3] 8. Surrounded Regions 9. Number of Islands #### Backtracking 10. Combination Sum 11. Subsets 12. Permutations #### Greedy Algorithms 13. Jump Game 14. Gas Station 15. Task Scheduler #### Sliding Window Technique 16. Minimum Size Subarray Sum 17. Longest Repeating Character Replacement #### Bit Manipulation 18. Single Number[^1] 19. Maximum Product of Word Lengths 20. Reverse Bits This list continues up until reaching approximately 100 items covering various categories including but not limited to Trees, Graphs, Sorting, Searching, Math, Design Patterns, etc.. Each category contains multiple representative questions that cover fundamental concepts as well as advanced techniques required by leading technology companies when conducting software engineering candidate assessments. For those interested in improving logical thinking through gaming activities outside traditional study methods, certain types of video games have been shown beneficial effects similar to engaging directly within competitive coding platforms [^4]. --related questions-- 1. How does participating in online coding competitions benefit personal development? 2. What specific advantages do DFS/BFS algorithms offer compared to other traversal strategies? 3. Can you provide examples illustrating how bit manipulation improves performance efficiency? 4. In what ways might regular participation in programming contests influence job interview success rates? 5. Are there any notable differences between solving problems on paper versus implementing solutions programmatically?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值