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

Commit 963cad7

Browse files
committed
Add: Rotting Oranges
1 parent 900072a commit 963cad7

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package rotting_oranges
2+
3+
func orangesRotting(grid [][]int) int {
4+
r, c := len(grid), len(grid[0])
5+
hasFresh, isRotten, rottens := false, false, make([]int, 0)
6+
for i := 0; i < r; i++ {
7+
for j := 0; j < c; j++ {
8+
if !hasFresh && grid[i][j] == 1 {
9+
hasFresh = true
10+
} else if grid[i][j] == 2 {
11+
rottens = append(rottens, i*c+j)
12+
}
13+
}
14+
}
15+
for _, p := range rottens {
16+
i, j := p/c, p%c
17+
for k := 0; k < 4; k++ {
18+
nr, nc := i+k-1, j+k-2
19+
if k == 0 {
20+
nc += 2
21+
} else if k == 3 {
22+
nr -= 2
23+
}
24+
if 0 <= nr && nr < r && 0 <= nc && nc < c && grid[nr][nc] == 1 {
25+
grid[nr][nc], isRotten = 2, true
26+
}
27+
}
28+
}
29+
if !hasFresh {
30+
return 0
31+
} else if !isRotten {
32+
return -1
33+
}
34+
ans := orangesRotting(grid)
35+
if ans == -1 {
36+
return -1
37+
}
38+
return ans + 1
39+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package rotting_oranges
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input [][]int
7+
expected int
8+
}
9+
10+
func TestOrangesRotting(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: [][]int{
14+
{2, 1, 1},
15+
{1, 1, 0},
16+
{0, 1, 1},
17+
},
18+
expected: 4,
19+
},
20+
{
21+
input: [][]int{
22+
{2, 1, 1},
23+
{0, 1, 1},
24+
{1, 0, 1},
25+
},
26+
expected: -1,
27+
},
28+
{
29+
input: [][]int{
30+
{0, 2},
31+
},
32+
expected: 0,
33+
},
34+
{
35+
input: [][]int{
36+
{1, 2},
37+
},
38+
expected: 1,
39+
},
40+
}
41+
for _, tc := range tests {
42+
output := orangesRotting(tc.input)
43+
if output != tc.expected {
44+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
45+
}
46+
}
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /