LeetCode 289---Game of Life

问题描述LeetCode 289—Game of Life

实现代码:

public class Problem289 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
    // 参考 https://discuss.leetcode.com/topic/65416/sharing-my-java-0ms-solution-o-1-extra-space
     public void gameOfLife(int[][] board) {
            int height = board.length;
            if (height==0) return;
            int width = board[0].length;
            if (width==0) return;

            for (int i=0; i<height; i++) {
                int memo1 = 0, memo2 = 0;  
                for (int j=0; j<width; j++) {
                    int cur = board[i][j], next=0, life = memo1+memo2;
                    memo1 = memo2;
                    memo2 = 0;
                    if (j==0) {  //first cell in a row, no memo
                        if (i>0) { 
                            memo1 += board[i-1][j] & 1;  //top
                        }
                        if (i<height-1) { 
                            memo1 += board[i+1][j];  //bottom
                        }
                        life+=memo1;
                    }
                    memo1+=cur;
                    if (j<width-1) {
                        life+= board[i][j+1];  //right
                        if (i>0) memo2+=board[i-1][j+1] & 1; //right top
                        if (i<height-1) memo2+=board[i+1][j+1];  //right bottom
                    }
                    life+=memo2;
                    //next state
                    if (life==3) next = 1;
                    else if (life==2) next = cur;
                    else next = 0;
                    //set merged state
                    board[i][j] = (next<<1) + cur;
                } 
            }
            //set state for next generation
            for (int i=0; i<height; i++) for (int j=0; j<width; j++) board[i][j] = board[i][j]>>1;
        }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值