2024/9/3 Hot100 graph 烂橘子

This commit is contained in:
linlihong 2024-09-03 17:41:43 +08:00
parent af0ac3a040
commit d90f5da080
1 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package com.cool.hot100.graph;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/03/14:25
* DayNumber 3
* Hard 2
* Level ?
*/
public class Num994 {
int[] rowChange = new int[] { 0, 1, -1, 0 };
int[] columnChange = new int[] { 1, 0, 0, -1 };
public int orangesRotting(int[][] grid) {
int rowLength = grid.length;
int columnLength = grid[0].length;
Queue<Integer> queue = new ArrayDeque<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < columnLength; j++) {
if (grid[i][j] == 2) {
int code = i * columnLength + j;
queue.add(code);
map.put(code, 0);
}
}
}
int res = 0;
while (!queue.isEmpty()) {
Integer code = queue.poll();
int row = code / columnLength;
int column = code % columnLength;
for (int i = 0; i < 4; i++) {
int cRow = row + rowChange[i];
int cColumn = column + columnChange[i];
if (cRow >= 0 && cRow < rowLength && cColumn >= 0 && cColumn < columnLength
&& grid[cRow][cColumn] == 1) {
grid[cRow][cColumn] = 2;
int cCode = cRow * columnLength + cColumn;
queue.add(cCode);
map.put(cCode, map.get(code) + 1);
res = map.get(cCode);
}
}
}
for (int[] ints : grid) {
for (int j = 0; j < columnLength; j++) {
if (ints[j] == 1) {
return -1;
}
}
}
return res;
}
}