1
+ namespace LeetCodeSolutions . Graph ;
2
+
3
+ public class SurroundedRegions
4
+ {
5
+ public void Solve ( char [ ] [ ] board )
6
+ {
7
+ // Handle edge cases
8
+ if ( board == null || board . Length == 0 ) return ;
9
+
10
+ int rows = board . Length ;
11
+ int cols = board [ 0 ] . Length ;
12
+
13
+ // Step 1: Mark all 'O's connected to borders as safe ('T')
14
+ // Check first and last column
15
+ for ( int row = 0 ; row < rows ; row ++ )
16
+ {
17
+ MarkSafeRegion ( board , row , 0 ) ;
18
+ MarkSafeRegion ( board , row , cols - 1 ) ;
19
+ }
20
+
21
+ // Check first and last row
22
+ for ( int col = 0 ; col < cols ; col ++ )
23
+ {
24
+ MarkSafeRegion ( board , 0 , col ) ;
25
+ MarkSafeRegion ( board , rows - 1 , col ) ;
26
+ }
27
+
28
+ // Step 2: Convert all remaining 'O's to 'X' and restore 'T's to 'O'
29
+ for ( int row = 0 ; row < rows ; row ++ )
30
+ {
31
+ for ( int col = 0 ; col < cols ; col ++ )
32
+ {
33
+ if ( board [ row ] [ col ] == 'O' )
34
+ {
35
+ // This 'O' is surrounded, so capture it
36
+ board [ row ] [ col ] = 'X' ;
37
+ }
38
+ else if ( board [ row ] [ col ] == 'T' )
39
+ {
40
+ // This was a safe 'O', restore it
41
+ board [ row ] [ col ] = 'O' ;
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ private void MarkSafeRegion ( char [ ] [ ] board , int row , int col )
48
+ {
49
+ int rows = board . Length ;
50
+ int cols = board [ 0 ] . Length ;
51
+
52
+ // Base case: out of bounds or not an 'O'
53
+ if ( row < 0 || row >= rows || col < 0 || col >= cols || board [ row ] [ col ] != 'O' )
54
+ {
55
+ return ;
56
+ }
57
+
58
+ // Mark this cell as safe
59
+ board [ row ] [ col ] = 'T' ;
60
+
61
+ // Check all four adjacent cells
62
+ MarkSafeRegion ( board , row + 1 , col ) ; // Down
63
+ MarkSafeRegion ( board , row - 1 , col ) ; // Up
64
+ MarkSafeRegion ( board , row , col + 1 ) ; // Right
65
+ MarkSafeRegion ( board , row , col - 1 ) ; // Left
66
+ }
67
+
68
+
69
+ [ Test ( Description = "https://leetcode.com/problems/surrounded-regions/" ) ]
70
+ [ Category ( "Medium" ) ]
71
+ [ Category ( "LeetCode" ) ]
72
+ [ Category ( "Surrounded Regions" ) ]
73
+ [ TestCaseSource ( nameof ( Input ) ) ]
74
+ [ Category ( "Graph" ) ]
75
+ [ Category ( "TopInterview" ) ]
76
+ public void Test1 ( ( char [ ] [ ] Output , char [ ] [ ] Input ) item )
77
+ {
78
+ this . Solve ( item . Input ) ;
79
+ Assert . That ( item . Input , Is . EqualTo ( item . Output ) ) ;
80
+ }
81
+
82
+ public static IEnumerable < ( char [ ] [ ] Output , char [ ] [ ] Input ) > Input =>
83
+ new List < ( char [ ] [ ] Output , char [ ] [ ] Input ) > ( )
84
+ {
85
+ ( [ [ 'X' , 'X' , 'X' , 'X' ] , [ 'X' , 'X' , 'X' , 'X' ] , [ 'X' , 'X' , 'X' , 'X' ] , [ 'X' , 'O' , 'X' , 'X' ] ] ,
86
+ [ [ 'X' , 'X' , 'X' , 'X' ] , [ 'X' , 'O' , 'O' , 'X' ] , [ 'X' , 'X' , 'O' , 'X' ] , [ 'X' , 'O' , 'X' , 'X' ] ] )
87
+ } ;
88
+ }
0 commit comments