JAVA 1ms easy and clearly recursive solution


  • 0
    D
    public class Solution {
    public void gameOfLife(int[][] board) {
        int rows = board.length;
        int cols = board[0].length;
        for(int i =0;i<rows;i++){
            for(int j =0;j<cols;j++){
                board[i][j] = countNeighbor(board,i,j,rows,cols);
            }
        }
        for(int i =0;i<rows;i++){
            for(int j =0;j<cols;j++){
                if(board[i][j]==3||board[i][j]==4||board[i][j]==-3)
                    board[i][j] = 1;
                else
                    board[i][j] = 0;
            }
        }
        
        
    }
    
    
    //0 to -8 represent itself dead and up to 8 live neighbors
    //1 to 9 represent it self live and up to 8 live neighbors
    
    public int countNeighbor(int [][] board,int i ,int j, int rows ,int cols){
        int count = 0;
        for(int a = i-1;a<=i+1;a++){
            for(int b = j-1;b<=j+1;b++){
                if(a>=0&&a<=rows-1&&b>=0&&b<=cols-1){
                    if(a!=i||b!=j){
                        if(board[a][b]>=1)
                            count++;
                    }
                }
            }
        }
        if(board[i][j]==0)
            return -count;
        else
            return count+1;
    }
    

    }


  • 0
    H

    looks good, but why do you call it recursive?


Log in to reply
 

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