/
dwite201102p5.java
84 lines (69 loc) · 1.91 KB
/
dwite201102p5.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* DWITE programming contest solutions
* February 2011 - Problem 5: "Cube World"
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/dwite-programming-contest-solutions
* https://github.com/nayuki/DWITE-programming-contest-solutions
*/
public final class dwite201102p5 extends DwiteSolution {
public static void main(String[] args) {
new dwite201102p5().run("DATA5.txt", "OUT5.txt");
}
private int rows;
private int cols;
private int[][] heights;
protected void runOnce() {
// Read grid
io.tokenizeLine();
rows = io.readIntToken();
cols = io.readIntToken();
heights = new int[rows][cols];
for (int i = 0; i < rows; i++) {
io.tokenizeLine();
for (int j = 0; j < cols; j++)
heights[i][j] = io.readIntToken();
}
// Find water capacity at each level
int water = 0;
for (int i = 0; i < 50; i++) {
water += getWaterCapacity(i);
}
io.println(water);
}
private int getWaterCapacity(int height) {
// Find cube-occupied cells
boolean[][] unusable = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
unusable[i][j] = heights[i][j] > height;
}
// Flood fill from the edges to disqualify cells
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1)
floodFill(unusable, i, j);
}
}
// Count remaining cells
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (!unusable[i][j])
count++;
}
}
return count;
}
private void floodFill(boolean[][] grid, int i, int j) {
if (i < 0 || i >= rows || j < 0 || j >= cols) // Out of bounds
return;
if (grid[i][j]) // Already filled
return;
grid[i][j] = true;
floodFill(grid, i , j - 1);
floodFill(grid, i , j + 1);
floodFill(grid, i - 1, j );
floodFill(grid, i + 1, j );
}
}