Skip to content

leetcode-0289 生命游戏 #226

@GuoLizhi

Description

@GuoLizhi

位运算

/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var gameOfLife = function(board) {
    const directions = [
        [0, 1],
        [0, -1],
        [1, 0],
        [-1, 0],
        [1, 1],
        [-1, -1],
        [1, -1],
        [-1, 1]
    ];
    if (board.length === 0) return
    const n = board.length;
    const m = board[0].length;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            let count = 0;
            for (let k = 0; k < 8; k++) {
                const x = directions[k][0] + i;
                const y = directions[k][1] + j;
                if (x < 0 || x >= n || y < 0 || y >= m) {
                    continue;
                }
                count += (board[x][y] & 1);
            }
            if (board[i][j] === 1) {
                if (count === 2 || count === 3) {
                    board[i][j] |= 2;
                }
            }
            if (board[i][j] === 0) {
                if (count === 3) {
                    board[i][j] |= 2;
                }
            }
        }
        
    }
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            board[i][j] >>= 1;
        }
    }
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions