Skip to content

Commit 2eecd57

Browse files
committed
'Surrounded Regions' soln
1 parent d309125 commit 2eecd57

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

leetcode/surrounded_regions.rs

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
///
2+
/// Problem: Surrounded Regions
3+
///
4+
/// Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally
5+
/// surrounded by 'X'.
6+
///
7+
/// A region is captured by flipping all 'O's into 'X's in that surrounded region.
8+
///
9+
/// Example 1:
10+
/// Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
11+
/// Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
12+
/// Explanation: Notice that an 'O' should not be flipped if:
13+
/// - It is on the border, or
14+
/// - It is adjacent to an 'O' that should not be flipped.
15+
/// The bottom 'O' is on the border, so it is not flipped.
16+
/// The other three 'O' form a surrounded region, so they are flipped.
17+
///
18+
/// Example 2:
19+
/// Input: board = [["X"]]
20+
/// Output: [["X"]]
21+
///
22+
/// Constraints:
23+
/// m == board.length
24+
/// n == board[i].length
25+
/// 1 <= m, n <= 200
26+
/// board[i][j] is 'X' or 'O'.
27+
///
28+
29+
// # Solution
30+
// Time complexity: O(m*n)
31+
// Space complexity: O(m*n)
32+
33+
impl Solution {
34+
pub fn solve(board: &mut Vec<Vec<char>>) {
35+
if board.is_empty() || board[0].is_empty() {
36+
return;
37+
}
38+
39+
let rows = board.len();
40+
let cols = board[0].len();
41+
42+
43+
for col in 0..cols {
44+
Self::dfs(board, 0, col as i32, rows as i32, cols as i32);
45+
Self::dfs(board, (rows - 1) as i32, col as i32, rows as i32, cols as i32);
46+
}
47+
48+
for row in 0..rows {
49+
Self::dfs(board, row as i32, 0, rows as i32, cols as i32);
50+
Self::dfs(board, row as i32, (cols - 1) as i32, rows as i32, cols as i32);
51+
}
52+
53+
for row in 0..rows {
54+
for col in 0..cols {
55+
if board[row][col] == 'O' {
56+
board[row][col] = 'X';
57+
} else if board[row][col] == 'E' {
58+
board[row][col] = 'O';
59+
}
60+
}
61+
}
62+
}
63+
64+
fn dfs(board: &mut Vec<Vec<char>>, row: i32, col: i32, rows: i32, cols: i32) {
65+
if row < 0 || row >= rows || col < 0 || col >= cols || board[row as usize][col as usize] != 'O' {
66+
return;
67+
}
68+
69+
board[row as usize][col as usize] = 'E';
70+
71+
Self::dfs(board, row + 1, col, rows, cols);
72+
Self::dfs(board, row - 1, col, rows, cols);
73+
Self::dfs(board, row, col + 1, rows, cols);
74+
Self::dfs(board, row, col - 1, rows, cols);
75+
}
76+
}

0 commit comments

Comments
 (0)