Game of Life

Problem

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  • Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  • Any live cell with two or three live neighbors lives on to the next generation.
  • Any live cell with more than three live neighbors dies, as if by over-population..
  • Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Write a function to compute the next state (after one update) of the board given its current state.

Solution

Mark by Adding 2 Solution

public class Solution {
    public void gameOfLife(int[][] board) {
        int m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int count = 0;
                for (int I = Math.max(0, i - 1); I < Math.min(m, i + 2); I++) {
                    for (int J = Math.max(0, j - 1); J < Math.min(n, j + 2); J++) {
                        count += board[I][J] > 1 ? board[I][J] - 2 : board[I][J];
                    }
                }
                if (count == 3 || count - board[i][j] == 3) board[i][j] += 2;
            }
        }
        for(int i = 0; i < m; i++) 
            for (int j = 0; j < n; j++) 
                board[i][j] = board[i][j] > 1 ? 1 : 0;
    } 
}

Analysis

Since each board has value 0 or 1, we mark by plussing 2
We check if current board survive by counting its neighbor's value
Because we might mark it before, we use -2 if it's >1
For all surviving situation, we can collect them as count == 3 || count - board[i][j] == 3
Notice that board[i][j] won't influence by marking cause it's looping in order
At the end, we know a board survived if it's >1

results matching ""

    No results matching ""