leetCode994. 腐爛的橘子 -BFS

引用
https://leetcode-cn.com/problems/rotting-oranges/

在給定的網格中,每個單元格可以有以下三個值之一:

  • 值 0 代表空單元格;
  • 值 1 代表新鮮橘子;
  • 值 2 代表腐爛的橘子。

每分鐘,任何與腐爛的橘子(在 4 個正方向上)相鄰的新鮮橘子都會腐爛。

返回直到單元格中沒有新鮮橘子爲止所必須經過的最小分鐘數。如果不可能,返回 -1。

示例 1:
在這裏插入圖片描述
輸入:[[2,1,1],[1,1,0],[0,1,1]]
輸出:4

示例 2:
輸入:[[2,1,1],[0,1,1],[1,0,1]]
輸出:-1
解釋:左下角的橘子(第 2 行, 第 0 列)永遠不會腐爛,因爲腐爛只會發生在 4 個正向上。

示例 3:
輸入:[[0,2]]
輸出:0
解釋:因爲 0 分鐘時已經沒有新鮮橘子了,所以答案就是 0

class Solution {
		 int row = 0;
		 int col = 0;
	public  int orangesRotting(int[][] grid) {
		row = grid.length;
		col = grid[0].length;
		// 遍歷 查看爛橘子的座標;
		Queue<ArrayList<Integer>> bucket = new LinkedList<ArrayList<Integer>>();
		int i, j;
		boolean hasFresh = false;
		for (i = 0; i < row; i++) {
			for (j = 0; j < col; j++) {
				if (grid[i][j] == 2) {
					ArrayList<Integer> pos = new ArrayList<Integer>();
					pos.add(i);
					pos.add(j);
					bucket.offer(pos);
				} else if (grid[i][j] == 1) {
					hasFresh = true;
				}
			}
		}
		// 沒有新鮮橘子 0秒
		if (!hasFresh) {
			return 0;
		}

		// 沒有變質橘子 -1
		if (bucket.size() == 0) {
			return -1;
		}
		
		int time = 0;
		// 遍歷壞橘子座標
		while (!bucket.isEmpty()) {
			// 每一批壞橘子的數量
			int count = bucket.size();
//			System.out.println("===第 "+time+" 輪感染= count:"+count+"==");
			for (int k = 0; k < count; k++) {
				ArrayList<Integer> pos = bucket.poll();
				int x = pos.get(0), y = pos.get(1);
//				System.out.println("壞橘子座標"+x+","+y);
				// 開始污染
				// 上
				if (check(x, y + 1) && grid[x][y+1] == 1) {
					grid[x][y+1] = 2;
					ArrayList<Integer> temp = new ArrayList<Integer>();
					temp.add(x);
					temp.add(y+1);
					bucket.offer(temp);
//					System.out.println("座標點被感染: "+x+","+ (y+1));
				}
				// 下
				if (check(x, y - 1) && grid[x][y-1] == 1) {
					grid[x][y-1] = 2;
					ArrayList<Integer> temp = new ArrayList<Integer>();
					temp.add(x);
					temp.add(y-1);
					bucket.offer(temp);
//					System.out.println("座標點被感染: "+x+","+ (y-1));
				}
				// 左
				if (check(x - 1, y) && grid[x-1][y] == 1) {
					grid[x-1][y] = 2;
					ArrayList<Integer> temp = new ArrayList<Integer>();
					temp.add(x-1);
					temp.add(y);
					bucket.offer(temp);
//					System.out.println("座標點被感染: "+(x-1)+","+ y);
				}
				// 右
				if (check(x + 1, y) && grid[x + 1][y] == 1) {
					grid[x+1][y] = 2;
					ArrayList<Integer> temp = new ArrayList<Integer>();
					temp.add(x+1);
					temp.add(y);
					bucket.offer(temp);
//					System.out.println("座標點被感染: "+(x+1)+","+ y);
				}
			}
			time++;
		}
		hasFresh = false;
		// 存在未感染的橘子
		for (i = 0; i < row; i++) {
			for (j = 0; j < col; j++) {
				if (grid[i][j] == 1) {
//					System.out.println("此座標點有新鮮橘子 i:"+i+"j:"+j);
					hasFresh = true;
					break;
				}
			}
		}
		if (hasFresh) {
			return -1;
		} else {
			return time-1;
		}
		
	}

	private  boolean check(int x, int y) {
		if (x >= 0 && x < row && y >= 0 && y < col) {
			return true;
		}
		return false;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章