LeetCode-289-Game of Life

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a247027417/article/details/83537124

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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

根据百度百科,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在1970年发明的细胞自动机。

给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞具有一个初始状态 live(1)即为活细胞, 或 dead(0)即为死细胞。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:

如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
根据当前状态,写一个函数来计算面板上细胞的下一个(一次更新后的)状态。下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。

示例:

输入: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
输出: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

【思路】

遍历board,然后遍历节点的周围节点,数出存活的细胞的数量然后存在数组中。根据存活的细胞的数量board中的细胞状态。

难点在于,对边界节点搜索周围节点的控制。

【代码】

class Solution {
    public void gameOfLife(int[][] board) {
    	
        int m = board.length;
        int n = board[0].length;
        int[][] live_cells = new int[m][n];
        for(int i = 0; i < m ; i++)
        	for(int j = 0; j < n ; j++)
        	{	live_cells[i][j] = 0;
        		for (int s = (i-1>=0?i-1:i); s <= ((i+1>=m?i:i+1)); s++)
        			for (int k = (j-1>=0?j-1:j); k <= ((j+1>=n?j:j+1)); k++)
        				if(s!=i || k!=j)
        					if(board[s][k]==1) 
        						live_cells[i][j] += 1;
        	}
        	for(int i = 0; i < m ; i++)
        		for(int j = 0; j < n ; j++){
        			if(board[i][j] == 1)
        				if(live_cells[i][j] < 2 || live_cells[i][j] > 3 ) 
        					board[i][j] = 0;
        			if(board[i][j] == 0)
        				if(live_cells[i][j] == 3)
        					board[i][j] = 1;
        		}
         }
}

猜你喜欢

转载自blog.csdn.net/a247027417/article/details/83537124
今日推荐