zoukankan      html  css  js  c++  java
  • Surrounded Regions 分类: Leetcode(广度优先搜索) 2015-04-23 11:01 18人阅读 评论(0) 收藏

    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


    广度优先搜索

    我们只需要从最外围的一圈中找到O,并且对其用广度优先搜索找到与外围O连通的路径,标记为'E',所有非E的都为X


    class Solution {
    public:
        int m ,n;
        void solve(vector<vector<char>> &board) {
            if (board.size() == 0) return;
            
            m = board.size();
            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] == 'E')
                        board[i][j] = 'O';
                }
            }
        }
    
    private:
        void bfs(vector<vector<char>> &board, int i, int j) {
            queue<int> q;
            visit(board,i,j,q);
            while(!q.empty()) {
                int cur = q.front();
                q.pop();
                const int x = cur/n;
                const int y = cur%n;
                visit(board, x-1, y, q);
                visit(board, x, y-1, q);
                visit(board, x+1, y, q);
                visit(board, x, y+1, q);
            }
        }
        
        void visit(vector<vector<char>> &board, int i, int j, queue<int> &q) {
            if(i < 0 || i > m-1 || j <0 || j > n-1 || board[i][j] != 'O')
                return;
            board[i][j] = 'E';
            q.push(i*n+j);
        }
        
    };






    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    JavaScript函数
    JavaScript数组知识点
    面向对象之继承及属性查找顺序
    面向对象二
    面向对象
    正则表达式补充
    垃圾回收机制、标记删除及分代回收
    hashlib、hmac、subprocess、configparser模块
    模块、起别名、from导入
    递归、匿名函数、内置函数
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656929.html
Copyright © 2011-2022 走看看