【Leetcode】Game of Life

题目链接:https://leetcode.com/problems/game-of-life/

题目:

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.

Follow up

  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?
思路:
 难点在如何in-place更新状态,这题跟remove二维数组0的题非常相似
难点都在于如何在判断的时候保存状态,首先状态是肯定要保存的,remove zero是保存在数组边界。
本题在循环程序中我们还是一个位置一个位置更新的,那么当一个位置更新了,这个位置成为其他位置的neighbor时,我们怎么知道其未更新的状态呢,我们可以令:0:死到死,1:活到活, 2:死到活,3:活到死,0和2表示原来的状态都是死。
算法:
	public void gameOfLife(int[][] board) {
		int c[] = { -1, -1, -1, 0, 0, 1, 1, 1 }, d[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				int liveNums = 0;
				for (int k = 0; k < 8; k++) {// 统计有多少活着的邻居
					if (i + c[k] >= 0 && i + c[k] < board.length && j + d[k] >= 0 && j + d[k] < board[0].length)
						if (board[i + c[k]][j + d[k]] == 1 || board[i + c[k]][j + d[k]] == 3)
							liveNums++;
				}
				System.out.println(board[i][j]+":"+liveNums);
				if (board[i][j] == 1) {// 更新状态
					if (liveNums < 2 || liveNums > 3) {
						board[i][j] = 3;
					}
				} else {
					if (liveNums == 3) {
						board[i][j] = 2;
					}
				}
			}
		}

		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				if (board[i][j] == 2) {
					board[i][j] = 1;
				}
				if (board[i][j] == 3) {
					board[i][j] = 0;
				}
			}
		}
	}



你可能感兴趣的:(【Leetcode】Game of Life)