Leetcode 130: Surrounded Regions
Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
For example,
X X X X X O O X X X O X X O X X
After running your function, the board should be:
X X X X X X X X X X X X X O X X
1 public class Solution { 2 private int[,] directions = new int[,] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 3 private const char mark = 'A'; 4 5 public void Solve(char[,] board) { 6 int rows = board.GetLength(0), cols = board.GetLength(1); 7 8 if (rows <= 1 || cols <= 1) return; 9 10 for (int i = 0; i < rows; i++) 11 { 12 if (board[i, 0] == 'O') 13 { 14 DFS(board, rows, cols, i, 0); 15 } 16 17 if (board[i, cols - 1] == 'O') 18 { 19 DFS(board, rows, cols, i, cols - 1); 20 } 21 } 22 23 for (int i = 0; i < cols; i++) 24 { 25 if (board[0, i] == 'O') 26 { 27 DFS(board, rows, cols, 0, i); 28 } 29 30 if (board[rows - 1, i] == 'O') 31 { 32 DFS(board, rows, cols, rows - 1, i); 33 } 34 } 35 36 for (int i = 0; i < rows; i++) 37 { 38 for (int j = 0; j < cols; j++) 39 { 40 if (board[i, j] == mark) 41 { 42 board[i, j] = 'O'; 43 } 44 else if (board[i, j] == 'O') 45 { 46 board[i, j] = 'X'; 47 } 48 } 49 } 50 } 51 52 private void DFS(char[,] board, int rows, int cols, int row, int col) 53 { 54 if (row < 0 || row >= rows || col < 0 || col >= cols || board[row, col] != 'O') 55 { 56 return; 57 } 58 59 board[row, col] = mark; 60 61 for (int i = 0; i < directions.GetLength(0); i++) 62 { 63 int r = row + directions[i, 0], c = col + directions[i, 1]; 64 65 DFS(board, rows, cols, r, c); 66 } 67 } 68 }