【发布时间】:2017-04-14 00:21:09
【问题描述】:
我正在研究康威的生命游戏以自己实现它,并遇到了以下带有规则的实现:
给定一个有 m x n 个单元格的棋盘,每个单元格都有一个初始状态活 (1) 或死 (0)。每个单元格与其八个邻居(水平、垂直、对角线)使用以下四个规则(取自上述维基百科文章)进行交互:
- 任何活细胞少于两个的活细胞都会死亡,好像是由于人口不足造成的。
- 任何有两三个活邻居的活细胞都可以传给下一代。
- 任何有超过三个活邻居的活细胞都会死亡,就好像人口过剩一样。..
- 任何只有三个活邻居的死细胞都会变成活细胞,就像通过繁殖一样。
以及实现(https://discuss.leetcode.com/topic/29054/easiest-java-solution-with-explanation):
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0) return;
int m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int lives = liveNeighbors(board, m, n, i, j);
// In the beginning, every 2nd bit is 0;
// So we only need to care about when will the 2nd bit become 1.
if (board[i][j] == 1 && lives >= 2 && lives <= 3) {
board[i][j] = 3; // Make the 2nd bit 1: 01 ---> 11
}
if (board[i][j] == 0 && lives == 3) {
board[i][j] = 2; // Make the 2nd bit 1: 00 ---> 10
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
board[i][j] >>= 1; // Get the 2nd state.
}
}
}
public int liveNeighbors(int[][] board, int m, int n, int i, int j) {
int lives = 0;
for (int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) {
for (int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) {
lives += board[x][y] & 1;
}
}
lives -= board[i][j] & 1;
return lives;
}
还有司机:
public static void main(String args[]) {
GameOfLife gl = new GameOfLife();
int[][] board = {
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}
};
gl.gameOfLife(board);
}
我的问题是,liveNeighbors() 中的 x 和 y 代表什么?不明白为什么需要Math.min() 和Math.max()。另外,lives 是否代表板上初始化生命的数量?
【问题讨论】: