p289

LeetCode p289 Game of Life 题解

1.题目:

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.

题意:

按照一定的规则,计算一个矩阵下一阶段的情况。
规则如下 一个细胞活着是1 死了是0
一个活细胞只有在相邻细胞为2个或者3个时才可以活下来。
一个死细胞在周围细胞有3个活细胞时能够活过来。

2.解题思路:

将以上白话文翻译为代码逻辑。
见代码。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
public class Solution {
public void gameOfLife(int[][] board) {
int n = board.length;
if (n < 1)
return;
int m = board[0].length;
if (m < 1)
return;
int[][] ans = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ans[i][j] = check(i, j, board);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
board[i][j] = ans[i][j];
}
}

}

public int check(int n, int m, int[][] board) {
int a = board[n][m];
int count = 0;
count = c(n - 1, m - 1, board) + c(n - 1, m, board)
+ c(n - 1, m + 1, board) + c(n, m - 1, board)
+ c(n, m + 1, board) + c(n + 1, m - 1, board)
+ c(n + 1, m, board) + c(n + 1, m + 1, board);

if (count > 3 || count < 2)
return 0;
if ((a == 0 && count == 3) || (a == 1 && count > 1 && count < 4)) {
return 1;
} else {
return 0;
}
}

public int c(int n, int m, int[][] board) {
if (n > -1 && n < board.length && m > -1 && m < board[0].length)
return board[n][m];
else {
return 0;
}

}
}


4.一些总结: