289. Game of Life

主要难点在于inplace,解决办法:
用4种特殊state标记,同时记录下current state和next state。
标记如下:
00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;
tips:必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态

代码如下:

public class Solution {
    public int f(int i, int j, int[][] board){
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length){
            return -1;
        }else{
            return board[i][j];
        }
    }

    public int liveNum(int i, int j, int[][] board){
        int count = 0;
        int[][] offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1}};
        for (int[] offset : offsets){
            if (f(i + offset[0], j + offset[1], board) % 2 == 1)
                count ++;
        }
        return count;
    }

    //00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;
    //必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态
    public void gameOfLife(int[][] board) {
        if (board.length == 0 || board[0].length == 0)
            return;
        int count;
        for(int i = 0; i < board.length; i ++){
            for(int j = 0; j < board[0].length; j ++){
                count = liveNum(i, j, board);
                if (board[i][j] % 2 == 1){  //live cell
                    if (count == 2 || count == 3)
                        board[i][j] += 2;
                }else{
                    if (count == 3){
                        board[i][j] += 2;
                    }
                }
            }
        }
        for(int i = 0; i < board.length; i ++){
            for(int j = 0; j < board[0].length; j ++){
                board[i][j] = board[i][j] / 2;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值