O(1)space/O(mn)time java solution. Calculates num of neigbours first


  • -1
    S
    public void gameOfLife(int[][] board) {
        if(board.length == 0)
            return;
        int m = board.length;
        int n = board[0].length;
    
        //Sets neighbour information.
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int numOfAliveNeigbour = (isCellAlive(board, i -1, j -1, m, n) +
                                    isCellAlive(board, i -1, j, m, n) +
                                    isCellAlive(board, i -1, j +1, m, n) +
                                    isCellAlive(board, i, j -1, m, n) +
                                    isCellAlive(board, i, j +1, m, n) +
                                    isCellAlive(board, i +1, j -1, m, n) +
                                    isCellAlive(board, i +1, j, m, n) +
                                    isCellAlive(board, i +1, j +1, m, n));
                //I only need to change it when the number of neigbhours are more than zero.
                if(numOfAliveNeigbour != 0)
                {
                    if(board[i][j] > 0)
                        board[i][j] = numOfAliveNeigbour;
                    else
                        board[i][j] = -1 * numOfAliveNeigbour;
                }
            }
        }
        
        //Sets the next state of board.
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                //For live cells.
                if(board[i][j] > 0)
                {
                    //If less than two neibhours or more than 3 neighbours
                    if((board[i][j] < 2) || (board[i][j] > 3))
                        board[i][j] = 0;
                    else
                        board[i][j] = 1;
                }
                //For dead cells
                else
                {
                    //If exactly 3 lives as neighbours
                    if(board[i][j] == -3)
                        board[i][j] = 1;
                    else
                        board[i][j] = 0;
                }
            }
        }
    }
    
    //If neighbour is alive
    private int isCellAlive(int[][] board, int i , int j, int m, int n)
    {
        if ((i < 0) || (i == m) || (j < 0) || (j == n))
            return 0;
        if (board[i][j] > 0)
            return 1;
        
        return 0;
    }

Log in to reply
 

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