1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Surrounded Regions

Posted on 2014-01-15 16:23  1957  阅读(1273)  评论(0编辑  收藏  举报

又sb了,去找什么X

关X毛线的事情,我们只需去找边缘的O

这些都是靠近边缘的不用变X

所以按BFS一次,靠近边缘的O都不用变X

 

第一次用C++的lambda 哈哈哈

 

class Solution {
public:
    void vist(vector<vector<char> >&board, int x , int y) {
        typedef pair<int,int> state;
        
        int n = board.size();
        int m = board.front().size();
        
        auto isValid = [&](const state& s) {
            int x = s.first;
            int y = s.second;
            if(x < 0 || x >= n || y < 0 || y >= m || board[x][y] != 'O')
                return false;
            return true;
        };
        auto expand = [&](const state& s) {
            int x = s.first;
            int y = s.second;
            vector<state> result;
            const state newState[] = {{x+1,y} , {x-1,y} , {x,y+1} , {x,y-1}};
            
            for(int i = 0 ; i < 4 ; ++i) {
                if(isValid(newState[i])) {
                    result.push_back(newState[i]);
                    board[newState[i].first][newState[i].second] = '+';
                }
            }
            return result;
        };
        
        queue<state> que;
        state start = {x , y};
        if(isValid(start)) {
            que.push(start);
            board[x][y] = '+';
        }
        while(!que.empty()) {
            state curr = que.front(); que.pop();
            auto result = expand(curr);
            for(auto x : result) que.push(x);
        }
    }
    void solve(vector<vector<char>> &board) {
        if(board.empty()) return ;
        //n * m board
        int n = board.size();
        int m = board.front().size();
        for(int i = 0 ; i < n ; ++i) {
            vist(board , i , 0);
            vist(board , i , m-1);
        }
        for(int i = 0 ; i < m ; ++i) {
            vist(board , 0 , i);
            vist(board , n-1 , i);
        }
        for(int i = 0 ; i < n ; ++i) {
            for(int j = 0 ; j < m ; ++j) {
                if(board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if(board[i][j] == '+') {
                    board[i][j] = 'O';
                }
            }
        }
    }
};