• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
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;
        }
    }
};

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

posted on 2016-05-08 13:00  ArgenBarbie  阅读(262)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3