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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值