289. Game of Life

来源:互联网 发布:戏曲分类知乎 编辑:程序博客网 时间:2024/05/22 20:57

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.

Follow up
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. 
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?

题目意思: 
根据维基百科条目 Conway’s Game of Life(康威生命游戏),康威生命游戏是英国数学家约翰·何顿·康威在1970年发明的细胞自动机。

给出一个m*n的细胞矩阵,每个细胞都有一个初始状态:生存(1)或死亡(0)。每个细胞的变化都与它周围8个细胞有关,规则如下:

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

题目要求:写一个函数,根据矩阵当前的状态,计算这个细胞矩阵的下一个状态。

看懂了题目就很好做了,

public class Solution {    public void gameOfLife(int[][] board) {        if(board == null || board.length == 0)            return;        for(int i=0;i<board.length;i++){            for(int j=0;j<board[0].length;j++){                getState(board,i,j);            }        }        for(int i=0;i<board.length;i++){            for(int j=0;j<board[0].length;j++){                setState(board,i,j);            }        }    }    /**     * 获取[i][j]周边的存活数,本身dead设为负数,本身live设为正数。     * 如果存活数为0,改用+-9表示     *      */    public static void getState(int[][]board,int i,int j){        int num=0,flag=board[i][j]>0?1:-1;        for(int k=i-1;k<=i+1;k++){            for(int x=j-1;x<=j+1;x++){                if((k != i || x!=j) && k>=0 && k<board.length && x>=0 && x<board[0].length && board[k][x]>0)                    num++;            }        }        board[i][j]=num==0?9*flag : num*flag;    }    public static void setState(int[][]board,int i,int j){        if(board[i][j] > 0){            if(board[i][j] < 2 || board[i][j] >3 ) board[i][j]=0;            if(board[i][j] ==2 || board[i][j] == 3) board[i][j]=1;        }else{            if(board[i][j] == -3) board[i][j]=1;            else board[i][j]=0;        }    }}


0 0
原创粉丝点击