题目
In a given grid, each cell can have one of three values:
- the value
0representing an empty cell; - the value
1representing a fresh orange; - the value
2representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]Output: -1Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]Output: 0Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 101 <= grid[0].length <= 10grid[i][j]is only0,1, or2.
题意
给定一个矩阵包含若干个新鲜橘子和烂橘子。每一分钟每个烂橘子相邻四个橘子都会腐烂,问经过几分钟只剩下烂橘子。
思路
先遍历一遍矩阵,将所有烂橘子的位置加入队列,并统计新鲜橘子的个数。每一分钟的过程相当于将当前队列中位置全部出栈,判断相邻4个位置是否有新鲜橘子,有则将其变为烂橘子并将其位置加入队列以便下一分钟的处理。最后判断还有没有新鲜橘子。
代码实现
Java
class Solution {public int orangesRotting(int[][] grid) {int count = 0;int minutes = 0;int[] xPlus = { 0, 1, 0, -1 };int[] yPlus = { 1, 0, -1, 0 };int m = grid.length, n = grid[0].length;Queue<Coor> q = new LinkedList<>();for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (grid[i][j] == 2) {q.offer(new Coor(i, j));} else if (grid[i][j] == 1) {count++;}}}while (!q.isEmpty()) {int size = q.size();for (int j = 0; j < size; j++) {Coor cur = q.poll();for (int i = 0; i < 4; i++) {int nextX = cur.x + xPlus[i];int nextY = cur.y + yPlus[i];if (isValid(m, n, nextX, nextY) && grid[nextX][nextY] == 1) {grid[nextX][nextY] = 2;count--;q.offer(new Coor(nextX, nextY));}}}if (!q.isEmpty()) minutes++;}return count == 0 ? minutes : -1;}private boolean isValid(int m, int n, int i, int j) {return i >= 0 && i < m && j >= 0 && j < n;}}class Coor {int x;int y;public Coor(int x, int y) {this.x = x;this.y = y;}}
