O(mn) Java with comments. Any optimization suggestions ?


  • 0
    public class Solution {
        public void gameOfLife(int[][] board) {
            int rows = board.length;
            int cols = 0;
            int newDeath = 2;
            int newBirth = 3;
            int[] dirX = new int[] {0, 0, 1, -1, -1, -1, 1, 1};
            int[] dirY = new int[] {1, -1, 0, 0, -1, 1, -1, 1};
        
            if (rows > 0)
            {
                cols = board[0].length;
            }
            
            if (rows == 0 && cols == 0)
            {
                return;
            }
            
            for(int i = 0; i < rows; i++)
            {
                for(int j = 0; j < cols; j++)
                {
                    int ones = 0;
                    for(int dir = 0 ; dir < 8; dir++)
                    {
                        int neighbourX = i + dirX[dir];
                        int neighbourY = j + dirY[dir];
                        if (neighbourX >= 0 && neighbourX < rows && neighbourY >= 0 && neighbourY < cols &&
                            (board[neighbourX][neighbourY] == 1 || board[neighbourX][neighbourY] == newDeath))
                        {
                            // newDeaths were previously 1
                            ones++;
                        }
                    }
                    
                    if (board[i][j] != 0 && (ones < 2 || ones > 3))
                    {
                        // Death
                        board[i][j] = newDeath;
                    }
                    else if (board[i][j] != 1 && ones == 3)
                    {
                        // Birth
                         board[i][j] = newBirth;
                    }
                }
            }
            
            for(int i = 0; i < rows; i++)
            {
                for(int j = 0; j < cols; j++)
                {
                    if (board[i][j] == newBirth)
                    {
                        board[i][j] = 1;
                    }
                    else if (board[i][j] == newDeath){
                        board[i][j] = 0;
                    }
                }
            }
        }
    }

Log in to reply
 

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