My C++ O(1) space solution - so easy to understand!


  • 2
    E
    class Solution {
    public:
        void gameOfLife(vector<vector<int>>& board) {
            int m = board.size();
            if(m == 0) {
                return;
            }
            int n = board[0].size();
            for(int i = 0 ; i < m ; ++i) {
                for(int j = 0 ; j < n ; ++j) {
                    int count = 0;
                    for(int p = max(0, i - 1) ; p < min(m, i + 2) ; ++p) {
                        for(int q = max(0, j - 1) ; q < min(n, j + 2) ; ++q) {
                            if(board[p][q] & 1) {
                                ++count;
                            }
                        }
                    }
                    if(count == 3 || count - board[i][j] == 3) {
                        board[i][j] = board[i][j] | 2;
                    }
                }
            }
            for(int i = 0 ; i < m ; ++i) {
                for(int j = 0 ; j < n ; ++j) {
                    board[i][j] = board[i][j] >> 1;
                }
            }
        }
    };

  • 0
    T

    Tip for counting: count += board[p][q] & 1;


Log in to reply
 

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