http://www.geeksforgeeks.org/flood-fill-algorithm-implement-fill-paint/
画板fill功能的实现,看描述第一反应是bfs遍历即可,但是这个算法似乎更多用dfs来实现
dfs实现:根据gfg上的code
public static void floodFill(int[][] screen , int x, int y, int color){
int prev = screen[x][y];
floodFillUtil(screen, x, y, prev, color);
}
public static void floodFillUtil(int[][] screen, int x, int y, int prev, int newc){
//base case
if(x < 0 || x >= screen.length || y < 0 || y >= screen[0].length){
return;
}
if(screen[x][y] != prev){
return;
}
screen[x][y] = newc;
//recursive N,E, W,S four direction dfs
floodFillUtil(screen, x + 1, y, prev, newc);
floodFillUtil(screen, x - 1, y, prev, newc);
floodFillUtil(screen, x, y + 1, prev, newc);
floodFillUtil(screen, x, y - 1, prev, newc);
}
BFS 实现,需要用queue
//bfs implement
public static class Pair{
int x, y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
}
public static void floodFillbfs(int[][] screen, int x, int y, int color){
int m = screen.length;
int n = screen[0].length;
if(screen == null || screen.length == 0 || x >= m || y >= n){
return;
}
//System.out.println( m + " " + n);
int prev = screen[x][y];
//screen[x][y] = color;
Queue<Pair> queue= new LinkedList<Pair>();
queue.offer(new Pair(x, y));
//mark visit
int[][] visit = new int[m][n];
int cx, cy;
while(!queue.isEmpty()){
Pair cur = queue.poll();
cx = cur.x;
cy = cur.y;
//reset color
screen[cx][cy] = color;
visit[x][y] = 1; // mark has modified
if(cx + 1 < m && screen[cx + 1][cy] == prev && visit[cx + 1][cy] == 0){
queue.offer(new Pair(cx + 1, cy));
}
if(cx - 1 >= 0 && screen[cx - 1][cy] == prev && visit[cx - 1][cy] == 0){
queue.offer(new Pair(cx - 1, cy));
}
if(cy + 1 < n && screen[cx][cy + 1] == prev && visit[cx ][cy + 1] == 0){
queue.offer(new Pair(cx , cy + 1));
}
if(cy - 1 >= 0 && screen[cx][cy -1] == prev && visit[cx ][cy - 1] == 0){
queue.offer(new Pair(cx , cy - 1));
}
}
}