Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit76d2c52

Browse files
add a solution for 994
1 parenta02e433 commit76d2c52

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,51 @@ public int orangesRotting(int[][] grid) {
9393
returnfresh.isEmpty() ?min : -1;
9494
}
9595
}
96+
97+
publicstaticclassSolution3 {
98+
/**
99+
* My original solution on 10/29/2021.
100+
*/
101+
publicintorangesRotting(int[][]grid) {
102+
intm =grid.length;
103+
intn =grid[0].length;
104+
intfreshOranges =0;
105+
Queue<int[]>queue =newLinkedList<>();
106+
boolean[][]visited =newboolean[m][n];
107+
for (inti =0;i <m;i++) {
108+
for (intj =0;j <n;j++) {
109+
if (grid[i][j] ==2) {
110+
queue.offer(newint[]{i,j});
111+
visited[i][j] =true;
112+
}elseif (grid[i][j] ==1) {
113+
freshOranges++;
114+
}
115+
}
116+
}
117+
intmins =0;
118+
int[]directions =newint[]{0,1,0, -1,0};
119+
while (!queue.isEmpty()) {
120+
intsize =queue.size();
121+
booleanhasOneToRot =false;
122+
for (inti =0;i <size;i++) {
123+
int[]curr =queue.poll();
124+
for (intj =0;j <directions.length -1;j++) {
125+
intnewx =directions[j] +curr[0];
126+
intnewy =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(newint[]{newx,newy});
132+
hasOneToRot =true;
133+
}
134+
}
135+
}
136+
if (hasOneToRot) {
137+
mins++;
138+
}
139+
}
140+
returnfreshOranges ==0 ?mins : -1;
141+
}
142+
}
96143
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
publicclass_994Test {
1111
privatestatic_994.Solution1solution1;
1212
privatestatic_994.Solution2solution2;
13+
privatestatic_994.Solution3solution3;
1314
privatestaticint[][]grid;
1415

1516
@BeforeClass
1617
publicstaticvoidsetUp() {
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
publicvoidtest6() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp