This solution is based on another that I found in the forum, I changed a few things.

```
class Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
// total will be filled with the sum of the distances of every reachable empty land from all buildings
vector<vector<int>> total(rows, vector<int>(cols, 0));
/** From the first building we find, we will try to reach all 0 lands (i.e. empty) and we will make them -1 in grid
Then from the second building we find, we will try to reach all -1 lands (i.e. empty and reachable from the previously found building) and we will make them -2 in grid
...
For the n'th building we find, we will try to reach all -(n-1) lands (i.e. empty and reachable from all the previously found buildings) and we will make them -n
etc.
*/
array<int, 5> dir = {0,1,0,-1,0};
// number of the building we are currently examining. We decrease the variable by 1 each time we finish examining a building.
int buildingNumber = 0;
for (int i=0; i<rows; ++i) {
for (int j=0; j<cols; ++j) {
if (grid[i][j] == 1) {
// distances will be filled with the distance of every reachable empty land from this specific building
vector<vector<int>> distances(rows, vector<int>(cols, 0));
queue<pair<int,int>> q;
pair<int,int> p(i,j);
q.push(p);
while (!q.empty()) {
pair<int,int> p2 = q.front();
q.pop();
int old_x = p2.first;
int old_y = p2.second;
for (int k=0; k<4; ++k) {
int new_x = old_x+dir[k];
int new_y = old_y+dir[k+1];
if (new_x>=0 && new_x<rows && new_y>=0 && new_y<cols && grid[new_x][new_y]==buildingNumber) {
distances[new_x][new_y] = distances[old_x][old_y]+1;
total[new_x][new_y] += distances[new_x][new_y];
pair<int,int> p3(new_x, new_y);
q.push(p3);
--grid[new_x][new_y];
}
}
}
--buildingNumber;
}
}
}
int min_dist = INT_MAX;
for (int i=0; i<rows; ++i) {
for (int j=0; j<cols; ++j) {
// We are only interested in empty lands that are reachable from all buildings
if (grid[i][j]==buildingNumber) {
min_dist = min(min_dist, total[i][j]);
}
}
}
return min_dist == INT_MAX ? -1 : min_dist;
}
};
```