【LeetCode】 289. Game of Life 生命游戏（Medium）（JAVA）

Leetcode 专栏收录该内容
326 篇文章 0 订阅

题目描述：

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):

1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population…
4. 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]
]


1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

题目大意

1. 如果活细胞周围八个位置的活细胞数少于两个，则该位置活细胞死亡；
2. 如果活细胞周围八个位置有两个或三个活细胞，则该位置活细胞仍然存活；
3. 如果活细胞周围八个位置有超过三个活细胞，则该位置活细胞死亡；
4. 如果死细胞周围正好有三个活细胞，则该位置死细胞复活；

解题方法

2、把变更后的值存在矩阵中，但是 0 --> 1 用 2 表示，1 --> 0 用 3 表示
3、最后遍历一遍，把 2 变为 0，3 变为 1

class Solution {
public void gameOfLife(int[][] board) {
if (board.length == 0 || board[0].length == 0) return;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
gH(board, i, j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j] %= 2;
}
}
}

int[][] ori = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};
public void gH(int[][] board, int i, int j) {
int count = 0;
for (int k = 0; k < ori.length; k++) {
int nI = i + ori[k][0];
int nJ = j + ori[k][1];
if (nI < 0 || nJ < 0 || nI >= board.length || nJ >= board[0].length) continue;
if (board[nI][nJ] == 1 || board[nI][nJ] == 2) count++;
}
if (count < 2 || count > 3) {
if (board[i][j] == 1) board[i][j] = 2;
} else if (count == 3) {
if (board[i][j] == 0) board[i][j] = 3;
}
}
}


• 0
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

01-22
10-02 1575

01-08 2075
04-28 42
09-19 1万+
10-21 1万+
03-18 337
01-11 2305
12-08 446
09-09 470

¥2 ¥4 ¥6 ¥10 ¥20

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