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

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/87738786