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 ++;
}
}
}
}