class Solution {
private:
int h;
int w;
inline bool top(int sr, int sc, pair<int, int> &result) {
if (sr > 0) {
result = make_pair((sr - 1), sc);
return true;
}
return false;
}
inline bool down(int sr, int sc, pair<int, int> &result) {
if (sr < (h - 1)) {
result = make_pair((sr + 1), sc);
return true;
}
return false;
}
inline bool left(int sr, int sc, pair<int, int> &result) {
if (sc > 0) {
result = make_pair(sr, (sc - 1));
return true;
}
return false;
}
inline bool right(int sr, int sc, pair<int, int> &result) {
if (sc < (w - 1)) {
result = make_pair(sr, sc + 1);
return true;
}
return false;
}
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
h = image.size();
w = image[0].size();
vector<vector<bool>> visit(h, vector<bool>(w, false));
queue<pair<int, int> > q;
int color = image[sr][sc];
image[sr][sc] = newColor;
visit[sr][sc] = true;
q.push(make_pair(sr,sc));
int count = 0;
while (!q.empty() && (count++ < 10)) {
pair<int, int> now = q.front();
q.pop();
pair<int, int> neighbor;
if (top(now.first, now.second, neighbor)) {
if (!visit[neighbor.first][neighbor.second] && (image[neighbor.first][neighbor.second] == color)) {
q.push(neighbor);
visit[neighbor.first][neighbor.second] = true;
image[neighbor.first][neighbor.second] = newColor;
}
}
if (down(now.first, now.second, neighbor)) {
if (!visit[neighbor.first][neighbor.second] && (image[neighbor.first][neighbor.second] == color)) {
q.push(neighbor);
visit[neighbor.first][neighbor.second] = true;
image[neighbor.first][neighbor.second] = newColor;
}
}
if (left(now.first, now.second, neighbor)) {
if (!visit[neighbor.first][neighbor.second] && (image[neighbor.first][neighbor.second] == color)) {
q.push(neighbor);
visit[neighbor.first][neighbor.second] = true;
image[neighbor.first][neighbor.second] = newColor;
}
}
if (right(now.first, now.second, neighbor)) {
if (!visit[neighbor.first][neighbor.second] && (image[neighbor.first][neighbor.second] == color)) {
q.push(neighbor);
visit[neighbor.first][neighbor.second] = true;
image[neighbor.first][neighbor.second] = newColor;
}
}
}
return image;
}
};
留言
張貼留言