Flood fill Algorithm – how to implement fill() in paint?

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));
			}
		}
		
	}
	



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值