From 0b8d6f3e20beff74db31451773bcbdd28410ff9e Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 21 Jun 2024 11:36:48 +0800 Subject: [PATCH] 20240621 Finished --- src/problem/mod.rs | 3 +- src/problem/p130_surrounded_regions.rs | 74 ++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 src/problem/p130_surrounded_regions.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1c2c0c7..68c2c51 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -154,4 +154,5 @@ mod p637_average_of_levels_in_binary_tree; mod p530_minimum_absolute_difference_in_bst; mod p230_kth_smallest_element_in_a_bst; mod p98_validate_binary_search_tree; -mod p200_number_of_islands; \ No newline at end of file +mod p200_number_of_islands; +mod p130_surrounded_regions; \ No newline at end of file diff --git a/src/problem/p130_surrounded_regions.rs b/src/problem/p130_surrounded_regions.rs new file mode 100644 index 0000000..88d66f1 --- /dev/null +++ b/src/problem/p130_surrounded_regions.rs @@ -0,0 +1,74 @@ +/** + * [130] Surrounded Regions + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + fn dfs(board: &mut Vec>, x: i32, y: i32, m: i32, n: i32) { + if x < 0 || x >= m || y < 0 || y >= n { + return; + } + + let (pos_x, pos_y) = (x as usize, y as usize); + + if board[pos_x][pos_y] != 'O' { + return; + } + + board[pos_x][pos_y] = 'A'; + + Self::dfs(board, x - 1, y, m, n); + Self::dfs(board, x + 1, y, m, n); + Self::dfs(board, x, y - 1, m, n); + Self::dfs(board, x, y + 1, m, n); + } + + pub fn solve(board: &mut Vec>) { + let m = board.len(); + let n = board[0].len(); + let (m_length, n_length) = (m as i32, n as i32); + + for i in 0..m { + if board[i][0] == 'O' { + Self::dfs(board, i as i32, 0, m_length, n_length); + } + if board[i][n - 1] == 'O' { + Self::dfs(board, i as i32, n_length - 1, m_length, n_length); + } + } + + for i in 0..n { + if board[0][i] == 'O' { + Self::dfs(board, 0, i as i32, m_length, n_length); + } + if board[m - 1][i] == 'O' { + Self::dfs(board, m_length - 1, i as i32, m_length, n_length); + } + } + + for i in 0..m { + for j in 0..n { + if board[i][j] == 'O' { + board[i][j] = 'X'; + } + if board[i][j] == 'A' { + board[i][j] = 'O'; + } + } + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_130() { + } +}