leetcode: Surrounded Regions
1 class Solution { 2 public: 3 void solve(vector<vector<char>>& board) { 4 if (board.empty()) return; 5 int n = board.size(); 6 int m = board[0].size(); 7 // Top-most line 8 for (int j = 0; j < m; ++j) 9 if (board[0][j] == 'O') 10 DFS(board, 0, j); 11 // Right-most column 12 for (int i = 1; i < n; ++i) 13 if (board[i][m-1] == 'O') 14 DFS(board, i, m - 1); 15 // Bottom-most line 16 for (int j = 0; j < m - 1; ++j) 17 if (board[n-1][j] == 'O') 18 DFS(board, n - 1, j); 19 // Left-most column 20 for (int i = 1; i < n - 1; ++i) 21 if (board[i][0] == 'O') 22 DFS(board, i, 0); 23 // Change interior 'O's to 'X's meanwhile restoring '#'s to 'O's 24 for (auto& vec: board) 25 for (char& c : vec) 26 if (c == 'O') 27 c = 'X'; 28 else if (c == '#') 29 c = 'O'; 30 } 31 32 void DFS(vector<vector<char>>& board, int i, int j) { 33 board[i][j] = '#'; 34 if (i - 1 >= 0 && board[i-1][j] == 'O') 35 DFS(board, i - 1, j); 36 if (j + 1 < board[0].size() && board[i][j+1] == 'O') 37 DFS(board, i, j + 1); 38 if (i + 1 < board.size() && board[i+1][j] == 'O') 39 DFS(board, i + 1, j); 40 if (j - 1 >= 0 && board[i][j-1] == 'O') 41 DFS(board, i, j - 1); 42 } 43 44 void BFS(vector<vector<char>>& board, int row, int col) { 45 board[row][col] = '#'; 46 queue<pair<int, int>> Q; 47 Q.push(make_pair(row, col)); 48 while (!Q.empty()) { 49 int i = Q.front().first; 50 int j = Q.front().second; 51 Q.pop(); 52 if (i - 1 >= 0 && board[i-1][j] == 'O') { 53 board[i-1][j] = '#'; 54 Q.push(make_pair(i - 1, j)); 55 } 56 if (j + 1 < board[0].size() && board[i][j+1] == 'O') { 57 board[i][j+1] = '#'; 58 Q.push(make_pair(i, j + 1)); 59 } 60 if (i + 1 < board.size() && board[i+1][j] == 'O') { 61 board[i+1][j] = '#'; 62 Q.push(make_pair(i + 1, j)); 63 } 64 if (j - 1 >= 0 && board[i][j-1] == 'O') { 65 board[i][j-1] = '#'; 66 Q.push(make_pair(i, j - 1)); 67 } 68 } 69 } 70 };