Rust 力扣 - 289. 生命游戏-题解代码

时间:2024-11-02 19:38:40
pub fn game_of_life(board: &mut Vec<Vec<i32>>) {
    let (m, n) = (board.len(), board[0].len());
    let mut rows = vec![vec![0; n].clone(); 2];

    let live = |board: &Vec<Vec<i32>>, i: usize,  j: usize| -> i32 {
        let mut lives = 0;

        // 上
        if i > 0 {
            lives += board[i - 1][j];
        }

        // 下
        if i + 1 < m {
            lives += board[i + 1][j];
        }
    
        // 左
        if j > 0 {
            lives += board[i][j - 1];

            // 左上
            if i > 0 {
                lives += board[i - 1][j - 1];
            }

            // 左下
            if i + 1 < m {
                lives += board[i + 1][j - 1];
            }
        }
    
        // 右
        if j + 1 < n {
            lives += board[i][j + 1];
            
            // 右上
            if i > 0 {
                lives += board[i - 1][j + 1];
            }

            // 右下
            if i + 1 < m {
                lives += board[i + 1][j + 1];
            }
        }

        if board[i][j] == 1 {
            if lives < 2 || lives > 3 {
                0
            } else {
                1
            }
        } else {
            if lives == 3 {
                1
            } else {
                0
            }
        }
    };

    for i in 0..n {
        rows[0][i] = live(board, 0, i);
    }

    for i in 1..m {
        for j in 0..n {
            rows[i % 2][j] = live(board, i, j);
        }

        for j in 0..n {
            board[i - 1][j] = rows[(i - 1) % 2][j];
        }
    }

    for i in 0..n {
        board[m - 1][i] = rows[(m - 1) % 2][i];
    }
}