
leetcode-cn.com/problems/fl…
代码如下
class Solution {
int[] dx = { -1, 1, 0, 0 };
int[] dy = { 0, 0, -1, 1 };
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int preColor = image[sr][sc];
if (preColor == newColor) {
return image;
}
int n = image.length, m = image[0].length;
Deque<int[]> queue = new LinkedList<int[]>();
queue.offer(new int[] { sr, sc });
image[sr][sc] = newColor;
while (!queue.isEmpty()) {
int[] now = queue.poll();
int x = now[0], y = now[1];
for (int i = 0; i < 4; i++) {
int newX = x + dx[i], newY = y + dy[i];
if (newX >= 0 && newX < n && newY >= 0 && newY < m && image[newX][newY] == preColor) {
queue.offer(new int[] {newX, newY});
image[newX][newY] = newColor;
}
}
}
return image;
}
}