Skip to content

Commit bf485db

Browse files
committed
Add GoldDigger task solution
1 parent cdf86a7 commit bf485db

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package by.andd3dfx.dynamic;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.EqualsAndHashCode;
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
/**
10+
* Золотоискатель находится на вершине горы, представленной в виде "треугольного" массива,
11+
* в каждой клетке которого находится какое-то кол-во золота:
12+
* <pre>
13+
* {0},
14+
* {5, 8},
15+
* {9, 8, 2},
16+
* {1, 3, 5, 6},
17+
* {6, 2, 4, 4, 5},
18+
* {9, 5, 3, 5, 5, 7},
19+
* {7, 4, 6, 4, 7, 6, 8}
20+
* </pre>
21+
* На каждом шаге он может двигаться только вниз или вправо.
22+
* Надо так проложить его маршрут, чтобы при спуске он собрал максимальное кол-во золота.
23+
* Ответ для данного массива: 37
24+
*/
25+
public class GoldDigger {
26+
27+
private final Map<Cell, Integer> cache = new HashMap<>();
28+
29+
public int solve(int[][] goldMatrix) {
30+
return maxGold(0, 0, goldMatrix);
31+
}
32+
33+
private int maxGold(int i, int j, int[][] m) {
34+
if (i == m.length - 1) {
35+
return m[i][j];
36+
}
37+
38+
var cell = new Cell(i, j);
39+
if (cache.containsKey(cell)) {
40+
return cache.get(cell);
41+
}
42+
43+
var result = m[i][j] + Math.max(
44+
maxGold(i + 1, j, m),
45+
maxGold(i + 1, j + 1, m)
46+
);
47+
cache.put(cell, result);
48+
return result;
49+
}
50+
51+
@EqualsAndHashCode
52+
@AllArgsConstructor
53+
private static class Cell {
54+
private int row;
55+
private int col;
56+
}
57+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package by.andd3dfx.dynamic;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.assertj.core.api.Assertions.assertThat;
7+
8+
public class GoldDiggerTest {
9+
10+
private GoldDigger goldDigger;
11+
12+
@Before
13+
public void setUp() throws Exception {
14+
goldDigger = new GoldDigger();
15+
}
16+
17+
@Test
18+
public void solveSimple() {
19+
var goldMatrix = new int[][]{
20+
{0},
21+
{5, 8},
22+
{9, 8, 2},
23+
};
24+
assertThat(goldDigger.solve(goldMatrix)).isEqualTo(16);
25+
}
26+
27+
@Test
28+
public void solve() {
29+
var goldMatrix = new int[][]{
30+
{0},
31+
{5, 8},
32+
{9, 8, 2},
33+
{1, 3, 5, 6},
34+
{6, 2, 4, 4, 5},
35+
{9, 5, 3, 5, 5, 7},
36+
{7, 4, 6, 4, 7, 6, 8}
37+
};
38+
assertThat(goldDigger.solve(goldMatrix)).isEqualTo(37);
39+
}
40+
}

0 commit comments

Comments
 (0)