【Leetcode】289. 生命游戏

41 阅读1分钟

leetcode-289.png

这里最主要的是处理状态 0->1 1->0, 这种就很混乱,所以接下来要引入另外的两个标记来进行计算

death to death  0  
live to live    1  
live to death   2  
death to live   3  

0和1的标记借助于题目里面的状态,2、3分别标记另外两种状态

var gameOfLife = function (board) {
    let rows = board.length,
        cols = board[0].length;
    var sum = function (r, c) {
        let num = 0;
        for (let i = -1; i <= 1; ++i) {
            for (let j = -1; j <= 1; ++j) {
                if (i === 0 && j === 0) continue;
                let row = r + i;
                let col = c + j;
                // 这里 1 和 2的状态都是活细胞,所以要进行判断
                if (
                    row >= 0 &&
                    row < rows &&
                    col >= 0 &&
                    col < cols &&
                    (board[row][col] === 1 || board[row][col] === 2)
                ) {
                    num++;
                }
            }
        }
        return num;
    };
    // death to death 0
    // live to live 1
    // live to death 2
    // death to live 3
    
    // 标记状态
    for (let i = 0; i < rows; ++i) {
        for (let j = 0; j < cols; ++j) {
            let lives = sum(i, j);
            if (board[i][j] === 1) {
                if (lives < 2 || lives > 3) {
                    board[i][j] = 2;
                }
            } else if (board[i][j] === 0) {
                if (lives === 3) {
                    board[i][j] = 3;
                }
            }
        }
    }
    // 恢复状态
    for (let i = 0; i < rows; ++i) {
        for (let j = 0; j < cols; ++j) {
            if (board[i][j] === 2) {
                board[i][j] = 0;
            } else if (board[i][j] === 3) {
                board[i][j] = 1;
            }
        }
    }
};