LeetCode:Game of Life

redis_v發表於2016-01-14

題目描述:

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?
思路:

題目要求只能原地解答,不能先計算一部分資料,再根據計算的一部分資料計算另一部分資料。所給資料又是二維陣列形式,所以,我想到了類似矩陣相乘的方法。

1、生成和給定陣列相同大小的新的陣列popu,用來統計每個數值對應的人的鄰居個數。

2、根據每個人的鄰居個數,重新計算原來的人是死是活。

    若原來的人是活的,鄰居個數等於2或3, 這個人活著,否則死去。

   若原來的人是死的,鄰居個數等於3,這個人活過來,否則仍然死的。

程式碼:

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
	int m = board.size();
	vector<int> board0 = board[0];
	int n =board0.size();
	vector<vector<int>> popu;
	for(int i = 0; i < m; i ++)
	{
		vector<int> popSingle;
		bool iDecrese = i - 1 >= 0;
		bool iIncrese = i + 1 < m;
		for(int j = 0; j < n; j ++)
		{
			int pop = 0;
			bool jDecrese = j - 1 >= 0;
			bool jIncrease = j + 1 < n;
			if(iDecrese)
			{
				pop += board[i - 1][j] == 1;
				if(jDecrese)
					pop += board[i - 1][j - 1] == 1;
				if(jIncrease)
					pop += board[i - 1][j + 1] == 1;
			}
			if(iIncrese)
			{
				pop += board[i + 1][j] == 1;
				if(jDecrese)
					pop += board[i + 1][j - 1] == 1;
				if(jIncrease)
					pop += board[i + 1][j + 1] == 1;
			}
			if(jDecrese)
				pop += board[i][j - 1] == 1;
			if(jIncrease)
				pop += board[i][j + 1] == 1;
			popSingle.push_back(pop);
		}
		popu.push_back(popSingle);
	}
	for(int i = 0; i < m; i ++)
	{
		for(int j = 0; j < n; j ++)
		{
			int pri = board[i][j];
			int bour = popu[i][j];
			board[i][j] = ((pri == 1) && (bour == 2 || bour == 3)) || ((pri == 0) && (bour == 3)) ? 1: 0;
		}
	}
}
};




相關文章