Skip to content

Commit 76d2c52

Browse files
add a solution for 994
1 parent a02e433 commit 76d2c52

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/main/java/com/fishercoder/solutions/_994.java

+47
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,51 @@ public int orangesRotting(int[][] grid) {
9393
return fresh.isEmpty() ? min : -1;
9494
}
9595
}
96+
97+
public static class Solution3 {
98+
/**
99+
* My original solution on 10/29/2021.
100+
*/
101+
public int orangesRotting(int[][] grid) {
102+
int m = grid.length;
103+
int n = grid[0].length;
104+
int freshOranges = 0;
105+
Queue<int[]> queue = new LinkedList<>();
106+
boolean[][] visited = new boolean[m][n];
107+
for (int i = 0; i < m; i++) {
108+
for (int j = 0; j < n; j++) {
109+
if (grid[i][j] == 2) {
110+
queue.offer(new int[]{i, j});
111+
visited[i][j] = true;
112+
} else if (grid[i][j] == 1) {
113+
freshOranges++;
114+
}
115+
}
116+
}
117+
int mins = 0;
118+
int[] directions = new int[]{0, 1, 0, -1, 0};
119+
while (!queue.isEmpty()) {
120+
int size = queue.size();
121+
boolean hasOneToRot = false;
122+
for (int i = 0; i < size; i++) {
123+
int[] curr = queue.poll();
124+
for (int j = 0; j < directions.length - 1; j++) {
125+
int newx = directions[j] + curr[0];
126+
int newy = directions[j + 1] + curr[1];
127+
if (newx >= 0 && newx < m && newy >= 0 && newy < n && grid[newx][newy] == 1 && !visited[newx][newy]) {
128+
freshOranges--;
129+
grid[newx][newy] = 2;
130+
visited[newx][newy] = true;
131+
queue.offer(new int[]{newx, newy});
132+
hasOneToRot = true;
133+
}
134+
}
135+
}
136+
if (hasOneToRot) {
137+
mins++;
138+
}
139+
}
140+
return freshOranges == 0 ? mins : -1;
141+
}
142+
}
96143
}

src/test/java/com/fishercoder/_994Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
public class _994Test {
1111
private static _994.Solution1 solution1;
1212
private static _994.Solution2 solution2;
13+
private static _994.Solution3 solution3;
1314
private static int[][] grid;
1415

1516
@BeforeClass
1617
public static void setUp() {
1718
solution1 = new _994.Solution1();
1819
solution2 = new _994.Solution2();
20+
solution3 = new _994.Solution3();
1921
}
2022

2123
@Test
@@ -66,6 +68,7 @@ public void test5() {
6668
public void test6() {
6769
grid = CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[2],[1]");
6870
assertEquals(1, solution2.orangesRotting(grid));
71+
assertEquals(1, solution3.orangesRotting(grid));
6972
}
7073

7174
}

0 commit comments

Comments
 (0)