java: add «407. Trapping Rain Water II»

Refactor to use attributes on the ‹Solution› class instead of passing
everything around…

URL:	https://leetcode.com/problems/trapping-rain-water-ii/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-01-19 22:12:10 +01:00
parent 00992317e8
commit 5b21547fd7
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -1,17 +1,25 @@
class Solution {
record Coord(int height, int y, int x) implements Comparable<Coord> {
private static boolean isValid(int width, int height, int y, int x) {
return y >= 0 && y < height && x >= 0 && x < width;
}
private int mapWidth = -1;
private int mapHeight = -1;
private int[][] heightMap = null;
public Coord add(int[][] heightMap, Coord other) {
private PriorityQueue<Coord> q = null;
private boolean[][] visited = null;
private boolean isValid(int y, int x) {
return y >= 0 && y < mapHeight && x >= 0 && x < mapWidth;
}
record Coord(int height, int y, int x) implements Comparable<Coord> {
public Coord add(Solution s, Coord other) {
var nextY = y + other.y;
var nextX = x + other.x;
if (!isValid(heightMap[0].length, heightMap.length, nextY, nextX)) {
if (!s.isValid(nextY, nextX)) {
return null;
}
return new Coord(Math.max(height, heightMap[nextY][nextX]), nextY, nextX);
return new Coord(Math.max(height, s.heightMap[nextY][nextX]), nextY, nextX);
}
@Override
@ -25,15 +33,7 @@ class Solution {
new Coord(0, 0, -1), new Coord(0, 0, 1), new Coord(0, -1, 0), new Coord(0, 1, 0)
};
private void initQueue(
int[][] heightMap,
PriorityQueue<Coord> q,
boolean[][] visited,
int n,
int y0,
int x0,
int dy,
int dx) {
private void initQueue(int n, int y0, int x0, int dy, int dx) {
for (int i = 0; i < n; ++i) {
var y = y0 + i * dy;
var x = x0 + i * dx;
@ -44,25 +44,27 @@ class Solution {
}
public int trapRainWater(int[][] heightMap) {
int width = heightMap[0].length, height = heightMap.length;
var visited = new boolean[height][width];
mapWidth = heightMap[0].length;
mapHeight = heightMap.length;
this.heightMap = heightMap;
var q = new PriorityQueue<Coord>();
visited = new boolean[mapHeight][mapWidth];
q = new PriorityQueue<>();
// initialize outer columns
initQueue(heightMap, q, visited, height, 0, 0, 1, 0);
initQueue(heightMap, q, visited, height, 0, width - 1, 1, 0);
initQueue(mapHeight, 0, 0, 1, 0);
initQueue(mapHeight, 0, mapWidth - 1, 1, 0);
// initialize outer rows
initQueue(heightMap, q, visited, width, 0, 0, 0, 1);
initQueue(heightMap, q, visited, width, height - 1, 0, 0, 1);
initQueue(mapWidth, 0, 0, 0, 1);
initQueue(mapWidth, mapHeight - 1, 0, 0, 1);
var totalVolume = 0;
while (!q.isEmpty()) {
var cell = q.poll();
for (var dir : DIRECTIONS) {
var neighbor = cell.add(heightMap, dir);
var neighbor = cell.add(this, dir);
if (neighbor == null || visited[neighbor.y()][neighbor.x()]) {
continue;
}