LeetCode 289.

Tags:

Complexity

  • Time complexity: O(n^2)

  • Space complexity: O(n^2)

Code

class Solution {
    public void gameOfLife(int[][] board) {
        // just consider which cells would live in next gen
        boolean[][] live = new boolean[board.length][board[0].length];
        for (int i=0; i<board.length; i++) {
            for (int j=0; j<board[0].length; j++) {
                int result = liveCount(board, i, j);
                if ((board[i][j] == 1 && (result == 2 || result == 3)) ||
                    (board[i][j] == 0 && result == 3)) {
                    live[i][j] = true;
                }
            }
        }

        for (int i=0; i<board.length; i++) {
            for (int j=0; j<board[0].length; j++) {
                if (live[i][j]) board[i][j] = 1;
                else board[i][j] = 0;
            }
        }

    }

    public int liveCount(int[][] board, int x, int y) {
        return isLive(board, x-1, y-1)+isLive(board, x-1, y)+isLive(board, x-1, y+1)+
        isLive(board, x, y-1)+isLive(board, x, y+1)+
        isLive(board, x+1, y-1)+isLive(board, x+1, y)+isLive(board, x+1, y+1);
    }

    public int isLive(int[][] board, int x, int y) {
        if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return 0;
        return board[x][y];
    }
}

Check out the description of this problem at LC 289.