LeetCode -- 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):


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.


这里是康威生命游戏的规则:
https://zh.wikipedia.org/wiki/康威生命游戏
生命游戏中,对于任意细胞,规则如下:
每个细胞有两种状态-存活或死亡,每个细胞与以自身为中心的周围八格细胞产生互动。(如图,黑色为存活,白色为死亡)


当前细胞为存活状态时,当周围低于2个(不包含2个)存活细胞时, 该细胞变成死亡状态。(模拟生命数量稀少)
当前细胞为存活状态时,当周围有2个或3个存活细胞时, 该细胞保持原样。
当前细胞为存活状态时,当周围有3个以上的存活细胞时,该细胞变成死亡状态。(模拟生命数量过多)
当前细胞为死亡状态时,当周围有3个存活细胞时,该细胞变成存活状态。 (模拟繁殖)


思路:
对每个单元格依次判断,符合规则直接赋值就行了。


实现代码:


public class Solution {
    public void GameOfLife(int[,] board) 
    {
        var row = board.GetLength(0);
    	var col = board.GetLength(1);
    	
    	var board2 = new int[row, col];
    	for(var i = 0;i < row; i++){
    		for(var j = 0;j < col; j++){
    			board2[i,j] = board[i, j];
    		}
    	}
	
    	
    	for(var i = 0; i < row ; i++){
    		for(var j = 0;j < col ; j++){
    			var lives = 0;
    			Check(i, j, board2, out lives);
    			if(board2[i,j] == 1){
    				if(lives < 2){
    					board[i,j] = 0;
    				}
    				if(lives == 2 || lives == 3){
    					continue;
    				}
    				if(lives > 3){
    					board[i,j] = 0;
    				}
    			}
    			else{
    				if(lives == 3){
    					board[i,j] = 1;
    				}
    			}
    		}
    	}
    }


private void Check(int row, int col, int[,] board, out int lives)
{
	var rowLen = board.GetLength(0);
	var colLen = board.GetLength(1);
	
	lives = 0;
	
	// top neighbers
	if(row > 0){
		if(board[row - 1, col] == 1){
			lives ++;
		}
		if(col > 0 && board[row - 1, col - 1] == 1){
			lives ++;
		}
		if(col < colLen - 1 && board[row - 1 ,col + 1] == 1){
			lives ++;
		}
	}
	//left and right
	if(col > 0 && board[row, col - 1] == 1){
		lives ++;
	}
	if(col < colLen - 1 && board[row, col + 1] == 1){
		lives ++;
	}
	// below neighbers
	if(row < rowLen - 1)
	{
		if(col > 0 && board[row + 1, col - 1] == 1){
			lives ++;
		}
		if(board[row + 1, col] == 1){
			lives ++;
		}
		if(col < colLen - 1 && board[row + 1, col + 1] == 1){
			lives ++;
		}
	}
}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值