`

Surrounded Regions (C++实现)

 
阅读更多
#define TEMP_FLAG 'Z'
#define O_FLAG 'O'
#define X_FLAG 'X'

class Solution {
public:    
    
    void solve(vector<vector<char>> &board) {
        int m = board.size();
        if(m <= 0) return;
        
        // deal with the border element
        for(int i = 0; i < m; i++) {
            if(i == 0 || i == m-1) {
                for(int j = 0; j < m; j++) 
                    infectAround(board, i, j, m);
            } else {
                infectAround(board, i, 0, m);
                infectAround(board, i, m-1, m);
            }
        }
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < m; j++) {
                if(board[i][j] == O_FLAG) board[i][j] = X_FLAG;
                if(board[i][j] == TEMP_FLAG) board[i][j] = O_FLAG;
            }
        }
    }
    
    void infectAround(vector<vector<char>> &board, int i, int j, int m) {
        if(i<0 || i>=m || j<0 || j>=m) return;
        if(board[i][j] != O_FLAG) return;
        board[i][j] = TEMP_FLAG;
        infectAround(board, i-1, j, m);
        infectAround(board, i+1, j, m);
        infectAround(board, i, j-1, m);
        infectAround(board, i, j+1, m);
    }
};

 

0
5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics