我学习生活的康威的游戏来实现它在我自己的,和整个以下实现的规则来:Java:如何实施康威的人生游戏?
由N个单元给定板有m个,每个单元都有活的初始状态(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
是否代表董事会初始化的生命数量?
我误解实施的可能性,为了澄清,在我接受/赞成答案之前,您能评论每次迭代发生了什么吗?真的有助于清理事情。 –
非常感谢。这清理了很多东西!还有几个问题。我仍然没有得到'生命' - 板子[i] [j]&1'部分。我们的广场没有1个?在'(1,2)'?减1的原因是什么?编辑:啊,这是我们正在寻找周围的方格本身,如果这本身是1,我们减去1,对吗? –
另外,board [i] [j] >> = 1'中的board [x] [y]&1'和>> = 1中的&1是做什么的? –