Description
Submission
class Solution {
using pii = pair<int, int>;
public:
vector<vector<int>> colorBorder(vector<vector<int>>& grid, int row, int col, int color) {
int m = grid.size(), n = grid[0].size();
queue<pii> q;
q.push({row, col});
int connectedColor = grid[row][col];
const vector<int> dirs {-1, 0, 1, 0, -1};
vector<vector<bool>> visited(m, vector<bool>(n, false));
auto rets = grid;
while(!q.empty()) {
auto [x, y] = q.front();
q.pop();
if(visited[x][y]) continue;
visited[x][y] = true;
for(int i = 0; i < 4; ++i) {
int nextX = x + dirs[i], nextY = y + dirs[i+1];
if(nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) {
rets[x][y] = color;
continue;
}
if(grid[nextX][nextY] != connectedColor) {
visited[nextX][nextY] = true;
rets[x][y] = color;
continue;
}
q.push({nextX, nextY});
}
}
return rets;
}
};
// [[1,2,1,2,1,2],
// [2,2,2,2,1,2],
// [1,2,2,2,1,2]]
// [[1,1,1,1,1,2],
// [1,2,1,1,1,2],
// [1,1,1,1,1,2]]