Approach
Breadth-first search
For Surroundedregions, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 78 lines of C++ from the credited upstream file surroundedRegions.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 7 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345 6class Solution {7public:8 void solve(vector<vector<char>> &board) {9 if (board.empty()) return;10 const int m = board.size();11 const int n = board[0].size();12 13 14 for (int i = 0; i < n; i++) {15 bfs(board, 0, i);16 bfs(board, m - 1, i);17 }18 19 20 for (int j = 1; j < m - 1; j++) {21 bfs(board, j, 0);22 bfs(board, j, n - 1);23 }24 25 for (int i = 0; i < m; i++)26 for (int j = 0; j < n; j++)27 28 if (board[i][j] == 'O')29 board[i][j] = 'X';30 31 else if (board[i][j] == '+')32 board[i][j] = 'O';33 } 34 35private:36 void bfs(vector<vector<char>> &board, int i, int j) {37 typedef pair<int, int> state_t;38 queue<state_t> q;39 const int m = board.size();40 const int n = board[0].size();41 42 auto is_valid = [&](const state_t &s) {43 const int x = s.first;44 const int y = s.second;45 if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O')46 return false;47 return true;48 };49 50 auto state_extend = [&](const state_t &s) {51 vector<state_t> result;52 const int x = s.first;53 const int y = s.second;54 const state_t new_states[4] = {{x-1,y}, {x+1,y},{x,y-1}, {x,y+1}};55 for(int k=0;k<4; ++k){56 if (is_valid(new_states[k])) {57 58 board[new_states[k].first][new_states[k].second] = '+';59 result.push_back(new_states[k]);60 } 61 }62 return result;63 };64 65 state_t start = { i, j };66 if (is_valid(start)) {67 board[i][j] = '+';68 q.push(start);69 }70 71 while (!q.empty()) {72 auto cur = q.front();73 q.pop();74 auto new_states = state_extend(cur);75 for (auto s : new_states) q.push(s);76 } 77 }78};