zoukankan      html  css  js  c++  java
  • 130. 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 {
        struct position
        {
            int x, y;
            position(int a, int b): x(a), y(b) {}
        };
    public:
        void solve(vector<vector<char>>& board) {
            int row = board.size();
            if(row <= 0)
                return;
            int col = board[0].size();
            if(col <= 0)
                return;
            queue<position> q;
            int i, j;
            for(i = 0; i < col; i++)
            {
                if('O' == board[0][i])
                    q.push(position(0, i));
                if('O' == board[row-1][i])
                    q.push(position(row-1, i));
            }
            for(i = 0; i < row; i++)
            {
                if('O' == board[i][0])
                    q.push(position(i, 0));
                if('O' == board[i][col-1])
                    q.push(position(i, col-1));
            }
            while(!q.empty())
            {
                position p = q.front();
                q.pop();
                board[p.x][p.y] = 'N';
                if(p.x > 0 && 'O' == board[(p.x)-1][p.y])
                    q.push(position((p.x)-1, p.y));
                if(p.x < row-1 && 'O' == board[(p.x)+1][p.y])
                    q.push(position((p.x)+1, p.y));
                if(p.y > 0 && 'O' == board[p.x][(p.y)-1])
                    q.push(position(p.x, (p.y)-1));
                if(p.y < col-1 && 'O' == board[p.x][(p.y)+1])
                    q.push(position(p.x, (p.y)+1));
            }
            for(i = 0; i < row; i++)
            {
                for(j = 0; j < col; j++)
                {
                    if('O' == board[i][j])
                        board[i][j] = 'X';
                    if('N' == board[i][j])
                        board[i][j] = 'O';
                }
                cout<<endl;
            }
        }
    };

    先找到四条边缘上面的字符,再找和这些字符相邻的字符。

  • 相关阅读:
    MVC5 Controller构造方法获取User为空解决方法
    js删除Array数组中的某个元素
    VS2015 工具箱 保存位置
    Mapper 赋值对应实体属性
    cookieHelper
    python3练习100题——007
    python3练习100题——006
    python3练习100题——005
    python3练习100题——004
    python3练习100题——003
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5470366.html
Copyright © 2011-2022 走看看