LeetCode 289. Game of Life

289. Game of Life

Medium

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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]

题意

在矩阵上定义一种元素与相邻元素值之间的迭代规则,求一次迭代

思路

非in-place算法非常简单,空间复杂度O(mn); 缓存上一行和本行,空间复杂度O(n); 更进一步,用不同的数字编码矩阵元素之前的状态与现在的状态,无需缓存一行,空间复杂度O(1). 本题用缓存行的方式实现。

代码

class Solution {
    public void gameOfLife(int[][] board) {
        int lu = 0, u = 0, ru = 0, l = 0, r = 0, ld = 0, d = 0, rd = 0, i = 0, j = 0, m = board.length, n = board[0].length, sum = 0;
        int[] pre = new int[n], cur = new int[n];
        for (i=0; i<m; ++i) {
            cur = Arrays.copyOf(board[i], board[i].length);
            for (j=0; j<n; ++j) {
                lu = j-1>=0? pre[j-1]: 0;
                u = pre[j];
                ru = j+1<n? pre[j+1]: 0;
                l = j-1>=0? l: 0;
                r = j+1<n? board[i][j+1]: 0;
                ld = i+1<m && j-1>=0? board[i+1][j-1]: 0;
                d = i+1<m? board[i+1][j]: 0;
                rd = i+1<m && j+1<n? board[i+1][j+1]: 0;
                sum = lu + u + ru + l + r + ld + d + rd;
                l = board[i][j];
                if (board[i][j] == 1) {
                    if (sum == 2 || sum == 3) {
                        board[i][j] = 1;
                    } else {
                        board[i][j] = 0;
                    }
                } else {
                    if (sum == 3) {
                        board[i][j] = 1;
                    } else {
                        board[i][j] = 0;
                    }
                }
            }
            pre = cur;
        }
    }
}
上一篇:Leetcode_1_Array_289生命游戏


下一篇:UnicodeEncodeError: 'latin-1' codec can't encode characters in position 289-