Problem 289

Posted by Ruizhi Ma on November 24, 2020

Solution URL

https://leetcode.com/submissions/detail/423810825/

代码

class Solution {
    public void gameOfLife(int[][] board) {
        //Ans: Solution
        //Time: O(M * N)
        //Space: O(M * N)
        final int[][] directions = {
            {-1, -1},
            {-1, 0},
            {-1, 1},
            {0, -1},
            {0, 1},
            {1, -1},
            {1, 0},
            {1, 1}
        };

        int rows = board.length;
        int cols = board[0].length;
        int[][] board_copy = new int[rows][cols];

        //copy the array
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                board_copy[i][j] = board[i][j];
            }
        }

        //traverse the board, to count the number of 1 in all directions
        //in order to decide whether the number will be live or die
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                //go to the eight directions of the current cell
                int cnt = 0;
                for(int[] dir: directions){
                    int r = i + dir[0];
                    int c = j + dir[1];

                    //check the bound
                    if(r >= 0 && r < rows && c >= 0 && c < cols){
                        //count the number of 1
                        if(board_copy[r][c] == 1) cnt++;
                    }
                }

                //follow the rule and update the cell
                //rule 1 and 3
                if((cnt < 2 || cnt > 3) && board[i][j] == 1) board[i][j] = 0;
                //rule 2
                if((cnt == 2 || cnt == 3) && board[i][j] == 1)  board[i][j] = 1;
                //rule 3
                if(cnt == 3 && board[i][j] == 0) board[i][j] = 1;
            }
        }
    }
}