[C++] Clean Code


  • 0
    class Solution {
    public:
        void gameOfLife(vector<vector<int>>& board) {
            vector<vector<int>> snap(board);
            for (int i = 0; i < snap.size(); i++) {
                for (int j = 0; j < snap[i].size(); j++) {
                    board[i][j] = fate(snap, i, j, snap[i][j]);
                }
            }
        }
    
    private:
        int fate(vector<vector<int>>& board, int i, int j, int alive) {
            int nbs[8][2] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1} };
            int liveNb = 0;
            for (int d = 0; d < 8; d++) {
                liveNb += isLive(board, i + nbs[d][0], j + nbs[d][1]);
            }
            return alive ? (liveNb == 2 || liveNb == 3) : (liveNb == 3);
        }
        
        int isLive(vector<vector<int>>& board, int i, int j) {
            return (0 <= i && i < board.size() && 0 <= j && j < board[i].size()) ? board[i][j] : 0;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.