LeetCode-289. 生命游戏-Java-medium

题目链接

法一(位运算 + 原地算法)
    /**
     * 方向向量
     */
    private static final int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
    private static final int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};

    /**
     * 法一(位运算 + 原地算法)
     * 1. 思路
     * (1)原有的最低位存储的是当前状态,可以利用倒数第二低位存储下一个状态
     * 2. 生死逻辑
     * (1)只要当前细胞周围有3个活细胞,不管当前细胞是死是活,下个状态都是活
     * (2)如果当前细胞是活,且周围有2个活细胞,则下个状态是活
     *
     * @param board
     */
    public void gameOfLife(int[][] board) {
        if (board.length == 0) {
            return;
        }
        int rowSize = board.length;
        int colSize = board[0].length;
        for (int row = 0; row < rowSize; row++) {
            for (int col = 0; col < colSize; col++) {
                int cnt = 0;
                for (int k = 0; k < 8; k++) { // 遍历[row, col]周围八个位置
                    int x = row + dx[k];
                    int y = col + dy[k];
                    if (x < 0 || x >= rowSize || y < 0 || y >= colSize) {
                        continue;
                    }
                    cnt += board[x][y] & 1; // 统计当前细胞周围活细胞个数,&1取最低位
                }
                if (cnt == 3 || (cnt == 2 && (board[row][col] & 1) == 1)) {
                    board[row][col] |= 0b10; // 设置下个状态为活,|= 0b10将倒数第二低位设为1
                }
            }
        }
        for (int row = 0; row < rowSize; row++) {
            for (int col = 0; col < colSize; col++) {
                board[row][col] >>= 1; // 最后一位去掉,倒数第二位变为更新后的状态
            }
        }
    }
本地测试
        /**
         * 289. 生命游戏
         */
        lay.showTitle(289);
        Solution289 sol289 = new Solution289();
        int[][] board289 = new int[][]{{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
        arrayOpt.showIntTwoDimArray(board289, board289.length);
        sol289.gameOfLife(board289);
        arrayOpt.showIntTwoDimArray(board289, board289.length);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值