algorithm code trick
1.二维数组上下左右移动时判断是否越界
https://www.cser.club/leetcode/#/leetcode/407.TrappingRainWaterII
// BFS上下左右
final int[][] neighbors = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!minHeap.isEmpty()) {
// 当前墙的高度
int tmpWall = minHeap.peek().height;
while (minHeap.peek() != null && minHeap.peek().height <= tmpWall) {
Cell tmpCell = minHeap.poll();
// BFS上下左右
for (int i = 0; i < 4; i++) {
int tmpRow = tmpCell.row + neighbors[i][0];
int tmpCol = tmpCell.col + neighbors[i][1];
// 判断上下左右是否在范围内,因为最外面一层肯定没用,所以判断条件随便写
if (tmpRow > 0 && tmpRow < ROWS && tmpCol > 0 && tmpCol < COLS && !visited[tmpRow][tmpCol]) {
visited[tmpRow][tmpCol] = true;
minHeap.add(new Cell(tmpRow, tmpCol, heightMap[tmpRow][tmpCol]));
res += Math.max(0, tmpWall - heightMap[tmpRow][tmpCol]); // 如果比墙矮,则可以存水。
}
}
}
}Last updated
Was this helpful?