I don't know why my code doesn't produce the correct results. So far, I think it's quite similar to yours. Thanks

class Solution {
vector<pair<int, int>> vd{ make_pair<int, int>(-1, 0), make_pair<int, int>(1, 0), make_pair<int, int>(0, 1), make_pair<int, int>(0, -1) };
public:
int shortestDistance(vector<vector<int>>& grid) {
if (grid.empty())
return 0;
int row = grid.size(), col = grid[0].size();
pair<int, int> t;
int walk = 0, res=INT_MAX;
vector<vector<int>> dist(row, vector<int>(col, 0));
for (int r = 0; r < row; r++)
for (int c = 0; c < col; c++)
{
if (grid[r][c] == 1)
{
int level = 1;
t.first = r;
t.second = c;
queue<pair<int, int>> q, nextQ;
res=INT_MAX;
q.push(t);
while (!q.empty())
{
t = q.front();
int rn, cn;
q.pop();
for (int i = 0; i < vd.size(); i++)
{
rn = t.first + vd[i].first;
cn = t.second + vd[i].second;
if (rn < 0 || rn >= row || cn<0 || cn >= col || grid[rn][cn]>0)
{
continue;
}
if (grid[rn][cn] == walk)
{
grid[rn][cn] = walk - 1;
dist[rn][cn] = level + 1;
res = min(res, dist[rn][cn]);
pair<int, int> nei;
nei.first = rn;
nei.second = cn;
nextQ.push(nei);
}
}
level++;
swap(q,nextQ);
}
walk--;
}
}
if (res == INT_MAX)
return -1;
else
return res;
}
};