An image
is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc)
representing the starting pixel (row and column) of the flood fill, and a pixel value newColor
, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
思路:BFS, DFS都可以做。
class Solution {
private class Node {
public int x;
public int y;
public int color;
public Node(int x, int y, int color) {
this.x = x;
this.y = y;
this.color = color;
}
}
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if(image == null || image.length == 0 || image[0].length == 0) {
return image;
}
int n = image.length;
int m = image[0].length;
boolean[][] visited = new boolean[n][m];
Queue<Node> queue = new LinkedList<Node>();
queue.offer(new Node(sr, sc, image[sr][sc]));
visited[sr][sc] = true;
int[] dx = {0,0,-1,1};
int[] dy = {-1,1,0,0};
while(!queue.isEmpty()) {
Node node = queue.poll();
int x = node.x;
int y = node.y;
int oldcolor = node.color;
// change color to new color;
image[x][y] = newColor;
for(int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if(0 <= nx && nx < n && 0 <= ny && ny < m
&& image[nx][ny] == oldcolor && !visited[nx][ny]) {
queue.offer(new Node(nx, ny, image[nx][ny]));
visited[nx][ny] = true;
}
}
}
return image;
}
}
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if(image == null || image.length == 0 || image[0].length == 0) {
return image;
}
int n = image.length;
int m = image[0].length;
boolean[][] visited = new boolean[n][m];
dfs(image, sr, sc, newColor, image[sr][sc], visited);
return image;
}
private void dfs(int[][] image, int x, int y, int newcolor, int oldcolor,
boolean[][] visited) {
int n = image.length;
int m = image[0].length;
if( x < 0 || x >= n || y < 0 || y >= m || visited[x][y]) {
return;
}
if(image[x][y] == oldcolor) {
image[x][y] = newcolor;
visited[x][y] = true;
dfs(image, x + 1, y, newcolor, oldcolor, visited);
dfs(image, x - 1, y, newcolor, oldcolor, visited);
dfs(image, x, y + 1, newcolor, oldcolor, visited);
dfs(image, x, y - 1, newcolor, oldcolor, visited);
}
}
}