人生第一次击败100%的用户,哈哈哈

leetcode 289 生命游戏

太简单了,不想说思路,因为没有思路,直接上代码

public class 生命游戏 {
    public static void main(String[] args) {
        int[][]a = {
                {0,1,0},
                {0,0,1},
                {1,1,1},
                {0,0,0}
        };
        gameOfLife(a);
    }
    public static void gameOfLife(int[][] board) {
        int row = board.length;
        int col = board[0].length;
        int[][] newBorad = new  int[row][col];
        // 从原数组复制一份到 copyBoard 中
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                newBorad[i][j] = board[i][j];
            }
        }

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                isAlive(board,i,j,newBorad);
            }
        }
        for (int i = 0; i < row; i++){
            for (int j = 0; j < col; j++){
                System.out.print(board[i][j]);
            }
            System.out.println();
        }
    }
    public static int calculateQuantity(int[][] board, int x, int y){
        int row = board.length; // 4
        int col = board[0].length; // 3
        int x1 = -1, y1 = -1, x2 = 1, y2 = 1;
        int sum = 0;
        if (x == 0){
            x1 += 1;
        }
        if (x == row-1){
            x2 -= 1;
        }
        if (y == 0){
            y1 += 1;
        }
        if (y == col-1){
            y2 -= 1;
        }
        for (int i = y1; i <= y2; i++){
            for (int j = x1; j <= x2; j++){
                if (board[x+j][y+i] == 1 ){
                    sum++;
                }
            }
        }
        if (board[x][y]==1){
            sum -= 1;
        }
        return sum;
    }
    public static int[][] isAlive(int[][] board, int x, int y,int[][] newBroad){
        int a = calculateQuantity(newBroad,x,y);
        if (a<2 || a>3){
            board[x][y] = 0;
        }
        if (a==3){
            board[x][y] = 1;
        }
        if (a==2 && board[x][y] ==1){
            board[x][y] = 1;
        }
        return board;
    }
}

附上截图:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值