Approach
Breadth-first search
For Shortest Distance from All Buildings, 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
- 67 lines of C++ from the credited upstream file 317.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.
1class Solution {2 public:3 int shortestDistance(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 const int nBuildings = getBuildingsCount(grid);8 int ans = INT_MAX;9 10 11 vector<vector<int>> dist(m, vector<int>(n));12 13 vector<vector<int>> reachCount(m, vector<int>(n));14 15 auto bfs = [&](int row, int col) -> bool {16 queue<pair<int, int>> q{{{row, col}}};17 vector<vector<bool>> seen(m, vector<bool>(n));18 seen[row][col] = true;19 int seenBuildings = 1;20 21 for (int step = 1; !q.empty(); ++step)22 for (int sz = q.size(); sz > 0; --sz) {23 const auto [i, j] = q.front();24 q.pop();25 for (const auto& [dx, dy] : kDirs) {26 const int x = i + dx;27 const int y = j + dy;28 if (x < 0 || x == m || y < 0 || y == n)29 continue;30 if (seen[x][y])31 continue;32 seen[x][y] = true;33 if (!grid[x][y]) {34 dist[x][y] += step;35 ++reachCount[x][y];36 q.emplace(x, y);37 } else if (grid[x][y] == 1) {38 ++seenBuildings;39 }40 }41 }42 43 return seenBuildings == nBuildings;44 };45 46 for (int i = 0; i < m; ++i)47 for (int j = 0; j < n; ++j)48 if (grid[i][j] == 1) 49 if (!bfs(i, j))50 return -1;51 52 for (int i = 0; i < m; ++i)53 for (int j = 0; j < n; ++j)54 if (reachCount[i][j] == nBuildings)55 ans = min(ans, dist[i][j]);56 57 return ans == INT_MAX ? -1 : ans;58 }59 60 private:61 int getBuildingsCount(vector<vector<int>>& grid) {62 return accumulate(63 grid.begin(), grid.end(), 0,64 [](int acc, vector<int>& row) { return acc + ranges::count(row, 1); });65 }66};67