文章目录
- 题目描述
- 题解思路
- 题解代码
- 题目链接
题目描述
题解思路
我们记录上一行和当前行转换之后的状态,当前行转换之后的状态计算完毕后调整上一行状态,直至最后一行状态计算完毕后调整最后一行状态
题解代码
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];
}
}
题目链接
https://leetcode.cn/problems/game-of-life/description/