zoukankan      html  css  js  c++  java
  • [LeetCode]Surrounded Regions

    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

    class Solution {
    public:
        int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
        void solveUtil(vector<vector<char> >& board, vector<vector<bool> >& visited, int ix, int iy, vector<pair<int,int> >& curPath, bool& isSurrounded)
        {
            int n = board.size();
            int m = board[0].size();
            queue<pair<int,int> > posQ;
            posQ.push(pair<int,int>(ix, iy));
            while(!posQ.empty())
            {
                int curX = posQ.front().first;
                int curY = posQ.front().second;
                posQ.pop();
                
                if(board[curX][curY] == 'O' && !visited[curX][curY])
                {
                    curPath.push_back(pair<int,int>(curX, curY));
                    visited[curX][curY] = true;
                    for(int k = 0; k < 4; ++k)
                    {
                        int newX = curX+dir[k][0];
                        int newY = curY+dir[k][1];
                        if(newX < 0 || newX >= n || newY < 0 || newY >= m) isSurrounded = false;
                        else if (!visited[newX][newY]) posQ.push(pair<int,int>(newX, newY));
                    }
                        
                }
            }
            
        }
        void solve(vector<vector<char>> &board) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int n = board.size();
            if(n == 0) return;
            int m = board[0].size();
            
            vector<vector<bool> > visited(n, vector<bool>(m, false));
            for(int i = 0; i < n; ++i)
            {
                for(int j = 0; j < m; ++j)
                {
                    vector<pair<int, int> > curPath;
                    bool isSurrounded = true;
                    if(!visited[i][j]) solveUtil(board, visited, i, j, curPath, isSurrounded);
                    if(isSurrounded)    
                    {
                        for(int i = 0; i < curPath.size(); ++i) 
                            board[curPath[i].first][curPath[i].second] = 'X';
                    }
                }
            }
            
        }
    };
    

      

  • 相关阅读:
    jmeter的基本功能使用详解
    服务器资源监控插件(jmeter)
    前端技术之--CSS
    前端技术之--HTML
    TCP/IP基础知识
    TCP/IP、Http的区别
    关于性能调优
    如何修改Docker已运行实例的端口映射
    Mysql 主从同步配置
    Presto的基本概念
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3598407.html
Copyright © 2011-2022 走看看