From 2a2df06e67970e5b686d2a4a91523a04f39d0271 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 4 May 2024 11:32:25 +0800 Subject: [PATCH] 20240504 Finished --- src/problem/mod.rs | 3 +- src/problem/p289_game_of_life.rs | 73 ++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 src/problem/p289_game_of_life.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 33d845c..5991f0b 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -120,4 +120,5 @@ mod p76_minimum_window_substring; mod p36_valid_sudoku; mod p54_spiral_matrix; mod p48_rotate_image; -mod p73_set_matrix_zeroes; \ No newline at end of file +mod p73_set_matrix_zeroes; +mod p289_game_of_life; \ No newline at end of file diff --git a/src/problem/p289_game_of_life.rs b/src/problem/p289_game_of_life.rs new file mode 100644 index 0000000..0bc665f --- /dev/null +++ b/src/problem/p289_game_of_life.rs @@ -0,0 +1,73 @@ +/** + * [289] Game of Life + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn game_of_life(board: &mut Vec>) { + let m = board.len(); + let n = board[0].len(); + + let directions = vec![(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]; + + for i in 0..m { + for j in 0..n { + let mut count = 0; + + for (delta_x, delta_y) in directions.iter() { + let x = i as i32 + *delta_x; + let y = j as i32 + *delta_y; + + if x >= 0 && x < m as i32 && y >= 0 && y < n as i32 { + let (x, y) = (x as usize, y as usize); + + // 本来就是活细胞或者刚死的活细胞 + if board[x][y] == 1 || board[x][y] == -1 { + count += 1; + } + } + } + + if board[i][j] == 1 { + if count < 2 || count > 3 { + // 死亡的活细胞 + board[i][j] = -1; + } + } + + if board[i][j] == 0 { + if count == 3 { + // 诞生的新细胞 + board[i][j] = 2; + } + } + } + } + + for i in 0..m { + for j in 0..n { + if board[i][j] == 2 { + board[i][j] = 1; + } + + if board[i][j] == -1 { + board[i][j] = 0; + } + } + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_289() { + } +}