Approach
Breadth-first search
For As Far from Land as Possible, 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
- 42 lines of C++ from the credited upstream file 1162.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 5 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.
1class Solution {2 public:3 int maxDistance(vector<vector<int>>& grid) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 const int m = grid.size();6 const int n = grid[0].size();7 queue<pair<int, int>> q;8 int water = 0;9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 if (grid[i][j] == 0)13 ++water;14 else15 q.emplace(i, j);16 17 if (water == 0 || water == m * n)18 return -1;19 20 int ans = 0;21 22 for (int d = 0; !q.empty(); ++d)23 for (int sz = q.size(); sz > 0; --sz) {24 const auto [i, j] = q.front();25 q.pop();26 ans = d;27 for (const auto& [dx, dy] : kDirs) {28 const int x = i + dx;29 const int y = j + dy;30 if (x < 0 || x == m || y < 0 || y == n)31 continue;32 if (grid[x][y] > 0)33 continue;34 q.emplace(x, y);35 grid[x][y] = 2; 36 }37 }38 39 return ans;40 }41};42