Another easy to understand JAVA solution


  • 0
    H

    Basically, use the ones to represent last state, and use the tens to represent next state.

    ...
    public class Solution {
    public void gameOfLife(int[][] board) {
    int rows = board.length;
    int cols = board[0].length;

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                int lives = gatherLives(board, row, col);
                
                if (lives < 2 && board[row][col] % 10 == 1) {
                    board[row][col] = 0 * 10 + board[row][col];
                } else if ((lives == 2 || lives == 3) && board[row][col] % 10 == 1) {
                    board[row][col] = 1 * 10 + board[row][col];
                } else if (lives == 3 && board[row][col] % 10 == 0) {
                    board[row][col] = 1 * 10 + board[row][col];
                } else {
                    board[row][col] = 0 * 10 + board[row][col];
                }
            }
        }
        
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                board[row][col] /= 10;
            }
        }
    }
    
    private int gatherLives(int[][] board, int row, int col) {
        int rows = board.length;
        int cols = board[0].length;
        int cnt = 0;
        
        for (int i = row - 1; i <= row + 1; i++) {
            if (i < 0 || i >= rows) {
                continue;
            }
            
            for (int j = col - 1; j <= col + 1; j++) {
                if (j < 0 || j >= cols) {
                    continue;
                }
                
                cnt += board[i][j] % 10;
            }
        }
        
        return cnt - board[row][col] % 10;
    }
    

    }
    ...


Log in to reply
 

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