An intuitive, simple and refreshing JAVA solution, O(1) space and O(nm) time complexity. Accepted 1ms


  • 0
    M
    public class Solution {
        public void gameOfLife(int[][] board) {
           // Store the adjacet value in the matrix
           // Make it negative if it was previously zero
            for(int i = 0; i < board.length; i++) {
                for(int j = 0; j < board[0].length; j++) {
                    if(board[i][j] == 0) board[i][j] = -1 * getadj(i, j, board.length, board[0].length, board);
                    else board[i][j] = getadj(i,j, board.length, board[0].length, board);
                }
            }
            
            // Now the board will contain the total number of 1's in adjacent cell
            // And the value will be negative if current board had 0 in this position
            // Now just manipulate again based on the conditions given in the matrix
            for(int i = 0; i < board.length; i++) {
                for(int j = 0; j < board[0].length; j++) {
                    if(board[i][j] > 0 ) {
                        if(board[i][j] == 2 || board[i][j] == 3) board[i][j] = 1;
                        else board[i][j] = 0;
                    } else {
                        if(board[i][j] == -3) board[i][j] = 1;
                        else board[i][j] = 0; 
                    } 
                } 
            }
     
        }
           public int getadj(int i, int j, int n, int m, int[][] mat) {
            int res = 0;
            if(i-1 >= 0 && (mat[i-1][j] > 0)) res++; // up
            if(j-1 >= 0 && mat[i][j-1] > 0) res++;   // left
            if(i+1 < n && mat[i+1][j] > 0) res++;    // down
            if(j+1 < m && mat[i][j+1] > 0) res++;    // right
            if(i -1 >= 0 && j-1 >= 0 && mat[i-1][j-1] > 0) res++; // dig - left - up
            if(i+1 < n && j+1 < m && mat[i+1][j+1] > 0) res++; // dig - right - down 
            if(i+1 < n && j-1 >= 0 && mat[i+1][j-1] > 0) res++; // dig - left - down
            if(i-1 >= 0 && j+1 < m && mat[i-1][j+1] > 0) res++; // dig - right - up
            if(res == 0 && mat[i][j] == 1) return 1; // Make sure if it was positive we don't make it zero
            return res;
           }
    }

  • 0
    Y

    use the sign flag to save old live status is good.


Log in to reply
 

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