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

    又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';
                    }
                }
            }
        }
    };
  • 相关阅读:
    LeetCode 264. Ugly Number II
    LeetCode 231. Power of Two
    LeetCode 263. Ugly Number
    LeetCode 136. Single Number
    LeetCode 69. Sqrt(x)
    LeetCode 66. Plus One
    LeetCode 70. Climbing Stairs
    LeetCode 628. Maximum Product of Three Numbers
    Leetcode 13. Roman to Integer
    大二暑假周进度报告03
  • 原文地址:https://www.cnblogs.com/x1957/p/3521055.html
Copyright © 2011-2022 走看看