leetcode #130 in cpp

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

Code:

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if(board.empty()) 
            return;
        vector<vector<int>> dir = {{0,1},{0,-1},{1,0},{-1,0}};
        int row = board.size()- 1;
        int col = board[0].size()- 1; 
        //put those O connected to Os on the border as 'F'
        char fill = 'F';
        char check = 'O';
        for(int i = 0; i <=row; i ++){
            if(board[i][0] == check) dfs(i,0,row,col, fill,check, board,dir);
            if(board[i][col] == check) dfs(i,col,row,col, fill, check,board,dir);

        }
        for(int i = 0; i <=col; i ++){
            if(board[0][i] == check) dfs(0,i,row,col, fill,check, board,dir);
             if(board[row][i] == check) dfs(row,i,row, col, fill, check,board,dir);
        }
        //change those O surrounded by X as X
        fill = 'X';
        check = 'O';
        for(int i = 1; i < row; i ++){
            for(int j = 1; j < col; j++){
                if(board[i][j] == check) dfs(i,j,row,col,fill,check,board,dir);
            }
        }
        //put those 0 connected to Os on the border as '0'
        fill = 'O';
        check = 'F';
        for(int i = 0; i <=row; i ++){
            if(board[i][0] == check) dfs(i,0,row,col, fill,check, board,dir);
            if(board[i][col] == check) dfs(i,col,row,col, fill, check,board,dir);

        }
     
        for(int i = 0; i <=col; i ++){
            if(board[0][i] == check) dfs(0,i,row,col, fill,check, board,dir);
            if(board[row][i] == check) dfs(row,i,row, col, fill,check, board,dir);

        }
        
    }
    void dfs(int x, int y, int &ru, int &cu, char fill,char check,vector<vector<char>>& board,vector<vector<int>> &dir){
        stack<int> xs; 
        stack<int> ys; 
        xs.push(x);
        ys.push(y);
        while(!xs.empty() && !ys.empty()){
            x = xs.top();
            y = ys.top();
            xs.pop();
            ys.pop();
            board[x][y] = fill;
            for(int i = 0; i < dir.size(); i ++){
                
                for(int j = 0; j < dir[i].size(); j ++){
                    if(x+dir[i][0] < 0 || x+dir[i][0] > ru || y+dir[i][1] < 0 || y+dir[i][1] > cu) 
                        continue;
                    if(board[x+dir[i][0]][y+dir[i][1]] == check) {
                        xs.push(x+dir[i][0]);
                        ys.push(y+dir[i][1]);
                    }
                }
            }
        }
        
        
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章