yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #289. Game of Life #248

Open yokostan opened 5 years ago

yokostan commented 5 years ago

Brute Force, use numbers to store the status:

class Solution {
    public void gameOfLife(int[][] board) {
        if (board == null || board.length == 0 || board[0].length == 0) return  ;
        int[] dx = {0, 1, 0, -1, 1, -1, 1, -1};
        int[] dy = {1, 0, -1, 0, 1, -1, -1, 1};

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                int count = 0;
                for (int k = 0; k < 8; k++) {
                    int x = i + dx[k];
                    int y = j + dy[k];
                    if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) {
                        if (board[x][y] > 0) count++;
                    }
                }
                if (board[i][j] > 0) {
                    if (count < 2) board[i][j] = 2;
                    if (count > 3) board[i][j] = 3;
                }
                if (board[i][j] <= 0) {
                    if (count == 3) board[i][j] = -1;
                }
            }
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 2 || board[i][j] == 3) board[i][j] = 0;
                if (board[i][j] == -1) board[i][j] = 1;
            }
        }
    }
}