289.生命游戏

原文链接:https://leetcode-cn.com/problems/game-of-life/submissions/

 

题目:

289.生命游戏

289.生命游戏

源代码:

class Solution289{ 
    public static void main(String[] args){
        int[][] board = new int[][]{{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
        gameOfLife(board);
        for(int i = 0;i < board.length;i++){
            for(int j = 0;j < board[0].length;j++){
                System.out.print(board[i][j]);
            }
            System.out.println();
        }

    }
    public static void gameOfLife(int[][] board) {
        if(board == null || board.length == 0){
            return;
        }
        int[][] newBoard = new int[board.length][board[0].length];
        for(int i = 0;i < board.length;i++){
            for(int j = 0;j < board[i].length;j++){
                newBoard[i][j] = 0;
                int sum = lifeSum(board,i,j);
                //System.out.println(sum);
                
                //如果存活的细胞数等于3,不管原细胞死活他的则下一状态总是活
                if(sum==3){
                    newBoard[i][j] = 1;
                }
                //如果周围存活细胞等于2,如果原细胞死,现在还是死,活,现在还是活
                //不在范围内其他细胞全部死亡
                else if(sum==2){
                    newBoard[i][j]=board[i][j];
                }
                //如果存活数等于其他数字,现在细胞肯定是死的
                //System.out.print(newBoard[i][j]);
            }
        }
        for(int i = 0;i < board.length;i++){
            for(int j = 0;j < board[i].length;j++){
                board[i][j] = newBoard [i][j];
            }
        }
    }
    public static int lifeSum(int[][] board,int i,int j){
        int num=0; //存储周围活细胞数
        //上边
        if(i!=0){
            num += board[i-1][j];
        }
        //左上角
        if(i!=0&&j!=0){
            num += board[i-1][j-1];
        }
        //左边
        if(j!=0){
            num += board[i][j-1];
        }
        //右上角
        if(i!=0&&j!=board[0].length-1){
            num += board[i-1][j+1];
        }
        //下边
        if(i!=board.length-1){
            num += board[i+1][j];
        }
        //右下角
        if(i!=board.length-1&&j!=board[0].length-1){
            num += board[i+1][j+1];
        }
        //右边
        if(j!=board[0].length-1){
            num += board[i][j+1];
        }
        //左下角
        if(i!=board.length-1&&j!=0){
            num += board[i+1][j-1];
        }
        return num;
    } 
}

 

上一篇:sql server 自增长id 允许插入显示值


下一篇:使用Aspose.Cells 设置chart的y坐标轴显示值