143、腐烂的橘子

题目描述:
在这里插入图片描述
在这里插入图片描述
使用的是dfs算法,当然也可以使用递归来进行
类似的一道题目
最短的桥
代码如下

class Solution {
    public int orangesRotting(int[][] grid) {
  //用来表示四个方向
		int dire[][] = {{1,0},
				{-1,0},
				{0,1},
				{0,-1}};
		//用于使用判断是否访问过的
		//用于循环的duilie
		Queue<int[]> duilie = new LinkedList<>();
		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid[i].length; j++) {
				//将腐烂的位置放入到队列中
				if(grid[i][j] == 2){
					/*int[] tems = new int[2];
					tems[0] = i;
					tems[1] = j;*/
					duilie.offer(new int[]{i,j});
				}
			}
		}
		int result = 0;
		while (!duilie.isEmpty()) {
			int size = duilie.size();
			//进行感染
			for (int i = 0; i < size; i++) {
				//得到一个坐标
				int []point = duilie.poll();
				for (int p[] : dire) {
					int x = point[0] + p[0];
					int y = point[1] + p[1];
					//在有效的范围内
					if(!(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length)){
						if(grid[x][y] == 1){
							grid[x][y] = 2;
							duilie.offer(new int[]{x,y});
						}
						
					}
				}
			}
			result ++;
		}
	
		for (int[] is : grid) {
			for (int i : is) {
				if(i == 1){
					return -1;
				}
			}
		}
		
		
		return result == 0? 0: result - 1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值