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.

Follow up:

  • 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.
  • 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?

接口public void gameOfLife(int[][] board)

2 思路

这是一种细胞自动机,每一个位置有两种状态,1为活细胞,0为死细胞,对于每个位置都满足如下的条件:

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

由于题目中要求我们用置换方法in-place来解题,所以我们就不能新建一个相同大小的数组,那么我们只能更新原有数组,但是题目中要求所有的位置必须被同时更新,但是在循环程序中我们还是一个位置一个位置更新的,那么当一个位置更新了,这个位置成为其他位置的neighbor时,我们怎么知道其未更新的状态呢,我们可以使用状态机转换:

  • 状态0: 死细胞转为死细胞
  • 状态1: 活细胞转为活细胞
  • 状态2: 活细胞转为死细胞
  • 状态3: 死细胞转为活细胞

最后我们对所有状态对2取余,那么状态0和2就变成死细胞,状态1和3就是活细胞,达成目的。我们先对原数组进行逐个扫描,对于每一个位置,扫描其周围八个位置,如果遇到状态1或2,就计数器累加1,扫完8个邻居,如果少于两个活细胞或者大于三个活细胞,而且当前位置是活细胞的话,标记状态2,如果正好有三个活细胞且当前是死细胞的话,标记状态3。完成一遍扫描后再对数据扫描一遍,对2取余变成我们想要的结果。
复杂度: Time: O(n) ; Space: O(1)

3 代码

      public void gameOfLife(int[][] board) {
		int m = board.length;
		int n = board[0].length;
		final int LIVE_TO_DEAD = 2;
		final int DEAD_TO_LIVE = 3;

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				int liveCell = getLiveCell(board, i, j);
				if (board[i][j] == 1) {
					if (liveCell < 2 || liveCell > 3) {
						board[i][j] = LIVE_TO_DEAD;
					}
				} else {
					if (liveCell == 3) {
						board[i][j] = DEAD_TO_LIVE;
					}
				}
			}
		}
		
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				board[i][j] = board[i][j] % 2;
			}
		}
	}

	private int getLiveCell(int[][] board, int i, int j) {
		int count = 0;
		int row = i - 1;
		int col = j - 1;
		for (int p = row; p < row + 3; p++) {
			for (int q = col; q < col + 3; q++) {
				if ((p >= 0 && p < board.length)
						&& (q >= 0 && q < board[0].length)) {
					if (board[p][q] == 1 || board[p][q] == 2) {
						count++;
					}
				}
			}
		}
		count = count - board[i][j];
		return count;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Game of Life的C++代码示例: ```cpp #include <iostream> #include <vector> #include <chrono> #include <thread> #include <cstdlib> using namespace std; class GameOfLife { private: vector<vector<int>> grid; int rows, columns; public: GameOfLife(int r, int c) : rows(r), columns(c) { grid.resize(rows, vector<int>(columns, 0)); } void initialize() { srand(time(NULL)); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { grid[i][j] = rand() % 2; } } } int getNeighbourCount(int row, int col) { int count = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { int r = row + i; int c = col + j; if (r >= 0 && r < rows && c >= 0 && c < columns && !(i == 0 && j == 0)) { count += grid[r][c]; } } } return count; } void nextGeneration() { vector<vector<int>> newGrid(rows, vector<int>(columns, 0)); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { int neighbourCount = getNeighbourCount(i, j); if (grid[i][j] == 0 && neighbourCount == 3) { newGrid[i][j] = 1; } else if (grid[i][j] == 1 && (neighbourCount == 2 || neighbourCount == 3)) { newGrid[i][j] = 1; } else { newGrid[i][j] = 0; } } } grid = newGrid; } void print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (grid[i][j] == 1) { cout << "* "; } else { cout << ". "; } } cout << endl; } } }; int main() { int rows = 40, columns = 40; GameOfLife gol(rows, columns); gol.initialize(); while (true) { gol.print(); gol.nextGeneration(); this_thread::sleep_for(chrono::milliseconds(100)); system("clear"); } return 0; } ``` 此代码实现了一个Game of Life模拟器,它使用随机值初始化单元格,并在每次迭代中计算每个单元格周围的邻居数量,然后使用规则进行更新。最后,它在控制台中打印游戏板并在每次迭代后清除屏幕。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值