【leetcode】289. 生命游戏

58 阅读1分钟

leetcode-289.png

修改状态的问题,这里比较难的一点在于状态叠加的问题,比如说之前这个细胞状态是0,但是现在修改成了1,但是在其他细胞相邻的地方,就会持续影响其他细胞的状态
这里需要引进其他状态来解决这个问题

// death to death 0
// live to live 1
// live to death 2
// death to live 3
var gameOfLife = function (board) {
    let rows = board.length, cols = board[0].length
    // 计算周围有多少个活细胞
    var sum = function (r, c) {
        let res = 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都是从活变成另一状态,要计算变之前的状态
                // 所以需要将 1 和 2 都并入计算
                if (row >= 0 &&
                    row < rows &&
                    col >= 0 &&
                    col < cols &&
                    (board[row][col] === 1 || board[row][col] === 2)) {
                    res++
                }
            }
        }
        return res
    }
    // 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 (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
            }
        }
    }
};