Surrounded Regions - LeetCode

Posted 真子集

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Surrounded Regions - LeetCode相关的知识,希望对你有一定的参考价值。

题目链接

https://leetcode.com/problems/surrounded-regions/

注意点

  • 边缘不算包围‘O’

解法

解法一:dfs。找处在边缘上的O然后dfs将与之相邻的O都改为#。处理完之后再把这时候的O改为X,#改为O即可

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int n  = board.size();
        for(int i = 0;i < n;i++)
        {
            for(int j = 0;j < board[i].size();j++)
            {
                if((i == 0 || i == n-1 || j == 0 ||j == board[i].size()-1) && board[i][j] == 'O') dfs(board,i,j);
            }
        }
        for(int i = 0;i < n;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 dfs(vector<vector<char>>& board,int i,int j)
    {
        if (board[i][j] == 'O')
        {
            board[i][j] = '#';
            if (i > 0 && board[i - 1][j] == 'O') 
                dfs(board, i - 1, j);
            if (j < board[i].size() - 1 && board[i][j + 1] == 'O') 
                dfs(board, i, j + 1);
            if (i < board.size() - 1 && board[i + 1][j] == 'O') 
                dfs(board, i + 1, j);
            if (j > 0 && board[i][j - 1] == 'O') 
                dfs(board, i, j - 1);
        }
    }
};

技术图片

解法二:bfs。基本上一样的思路,还是找处在边缘上的O然后bfs将与之相邻的O都改为#。处理完之后再把这时候的O改为X,#改为O即可

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int n  = board.size();
        for(int i = 0;i < n;i++)
        {
            for(int j = 0;j < board[i].size();j++)
            {
                if((i == 0 || i == n-1 || j == 0 ||j == board[i].size()-1) && board[i][j] == 'O') dfs(board,i,j);
            }
        }
        for(int i = 0;i < n;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 dfs(vector<vector<char>>& board,int i,int j)
    {
        if (board[i][j] == 'O')
        {
            board[i][j] = '#';
            if (i > 0 && board[i - 1][j] == 'O') 
                dfs(board, i - 1, j);
            if (j < board[i].size() - 1 && board[i][j + 1] == 'O') 
                dfs(board, i, j + 1);
            if (i < board.size() - 1 && board[i + 1][j] == 'O') 
                dfs(board, i + 1, j);
            if (j > 0 && board[i][j - 1] == 'O') 
                dfs(board, i, j - 1);
        }
    }
};

技术图片

小结

  • 这道题dfs和bfs效率都差不多

以上是关于Surrounded Regions - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

Surrounded Regions - LeetCode

Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

[LintCode] Surrounded Regions

130. Surrounded Regions