733. 图像渲染 简单DFS

733. 图像渲染

难度:简单
2020/8/16每日一题打卡√
题目描述
在这里插入图片描述

解题思路
题目真的又臭又长,但是读懂之后发现就是单纯的简单的图搜索问题,dfs或者bfs都能搞定

DFS

写dfs的时候总忘记加访问数组,结果就爆栈

		    /*
		     * 733. 图像渲染
		     * 2020/8/16
		     * 难度:简单
		     */
		    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
		    	boolean[][] visit = new boolean[image.length][image[0].length];
		    	dfsFloodFill(image, sr, sc, newColor, image[sr][sc],visit);
		    	return image;
		    }
		    
		    public void dfsFloodFill(int[][] image, int sr, int sc, int newColor,int oldColor,boolean[][] visit) {
		    	System.out.println(sr+" "+sc);
		    	//如果数组越界或者不等于开始节点的颜色值
		    	if(sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != oldColor || visit[sr][sc]) {
		    		return;
		    	}
		    	
		    	image[sr][sc] = newColor;
		    	visit[sr][sc] = true;
		    	dfsFloodFill(image, sr+1, sc, newColor, oldColor,visit);
		    	dfsFloodFill(image, sr-1, sc, newColor, oldColor,visit);
		    	dfsFloodFill(image, sr, sc+1, newColor, oldColor,visit);
		    	dfsFloodFill(image, sr, sc-1, newColor, oldColor,visit);
		    }

在这里插入图片描述

BFS

就是套模板

public int[][] floodFill1(int[][] image, int sr, int sc, int newColor) {
		    	int[][] move = new int[][] {{1,0},{-1,0},{0,1},{0,-1}};
		    	boolean[][] visit = new boolean[image.length][image[0].length];
		    	Queue<Point> queue = new LinkedList<>();
		    	
		    	queue.add(new Point(sr, sc));
		    	int oldColor = image[sr][sc];
		    	while(!queue.isEmpty()) {
		    		Point temp = queue.poll();
		    		visit[temp.x][temp.y] = true;
		    	    image[temp.x][temp.y] = newColor;
		    		for (int i = 0; i < move.length; i++) {
						int x = temp.x + move[i][0];
						int y = temp.y + move[i][1];
						
						if(x < 0 || x >= image.length || y < 0 || y >= image[0].length || image[x][y] != oldColor || visit[x][y]) {
							System.out.println(x+" "+y);
				    		continue;
						}else {
							queue.add(new Point(x, y));
						}	
					}
		    	}
		    	return image;
		    }

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值