Simple solution in java


  • 0
    A
    public class Solution {
    // the adder function to add the values around the specific cell
        public int inteladd(int[][] board,int i,int j){
            return board[i][j+1]+board[i+1][j]+board[i+1][j+1]+board[i-1][j+1]+board[i+1][j-1]+board[i-1][j]+board[i][j-1]+board[i-1][j-1];
        }
        
        public void gameOfLife(int[][] board){
    //create a bigger 2d matrix to avoid some boundries situations :(
            int[][] bigbox = new int[board.length+2][board[0].length+2];
            for(int i = 0; i < board.length; i++){
                for(int j = 0; j < board[0].length; j++){
                    bigbox[i+1][j+1] = board[i][j];
                }
            }
            for(int i = 0; i < board.length; i++){
                for(int j = 0; j < board[0].length; j++){
                    if(bigbox[i+1][j+1]==0&&(inteladd(bigbox,i+1,j+1)==3)){
                        board[i][j] = 1;
                    }else if(bigbox[i+1][j+1]==1&&(inteladd(bigbox,i+1,j+1)>3)){
                        board[i][j] = 0;                    
                    }else if(bigbox[i+1][j+1]==1&&(inteladd(bigbox,i+1,j+1)<2)){
                        board[i][j] = 0;                         
                    }
                }
            }
        }
    }
    

    Have fun


Log in to reply
 

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