-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Labels
Description
位运算
/**
* @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;
}
}
};