LeetCode -- Game of Life

来源:互联网 发布:knn算法matlab代码 编辑:程序博客网 时间:2024/05/16 07:20
题目描述:


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 neighbersif(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 rightif(col > 0 && board[row, col - 1] == 1){lives ++;}if(col < colLen - 1 && board[row, col + 1] == 1){lives ++;}// below neighbersif(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 ++;}}}}


0 0