- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 53 lines of C++ from the credited upstream file 2257.cpp.
- The implementation visibly relies on sequence storage.
- 10 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int countUnguarded(int m, int n, vector<vector<int>>& guards,4 vector<vector<int>>& walls) {5 int ans = 0;6 vector<vector<char>> grid(m, vector<char>(n));7 vector<vector<char>> left(m, vector<char>(n));8 vector<vector<char>> right(m, vector<char>(n));9 vector<vector<char>> up(m, vector<char>(n));10 vector<vector<char>> down(m, vector<char>(n));11 12 for (const vector<int>& guard : guards)13 grid[guard[0]][guard[1]] = 'G';14 15 for (const vector<int>& wall : walls)16 grid[wall[0]][wall[1]] = 'W';17 18 for (int i = 0; i < m; ++i) {19 char lastCell = 0;20 for (int j = 0; j < n; ++j)21 recordOrFill(grid[i][j], lastCell, left[i][j]);22 lastCell = 0;23 for (int j = n - 1; j >= 0; --j)24 recordOrFill(grid[i][j], lastCell, right[i][j]);25 }26 27 for (int j = 0; j < n; ++j) {28 char lastCell = 0;29 for (int i = 0; i < m; ++i)30 recordOrFill(grid[i][j], lastCell, up[i][j]);31 lastCell = 0;32 for (int i = m - 1; i >= 0; --i)33 recordOrFill(grid[i][j], lastCell, down[i][j]);34 }35 36 for (int i = 0; i < m; ++i)37 for (int j = 0; j < n; ++j)38 if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' &&39 up[i][j] != 'G' && down[i][j] != 'G')40 ++ans;41 42 return ans;43 }44 45 private:46 void recordOrFill(char currCell, char& lastCell, char& infoCell) {47 if (currCell == 'G' || currCell == 'W')48 lastCell = currCell;49 else50 infoCell = lastCell;51 }52};53