for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (grid[i][j] == 1) q[++tt] = {i, j}; } }
// determine special situation int qsize = tt - hh + 1; if (qsize == R * C || !qsize) return res;
for (; tt >= hh; ++hh) { // pop head int r = q[hh].first, c = q[hh].second; for (int i = 0; i < 4; i++) { int ner = r + dr[i], nec = c + dc[i]; if (ner < 0 || ner > R - 1 || nec < 0 || nec > C - 1 || grid[ner][nec]) continue; grid[ner][nec] = grid[r][c] + 1; q[++tt] = {ner, nec}; } }
for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { res = max(res, grid[i][j]); //cout << grid[i][j] << ' '; } //cout << endl; } return res - 1; } };