LeetCode/cs/map-of-highest-peak.cs
2025-01-22 22:50:46 +01:00

59 lines
1.6 KiB
C#

using Coord = (int x, int y);
public class Solution {
private static readonly int UNSET = -1;
private static readonly Coord[] DIRECTIONS = [
(0, 1),
(0, -1),
(1, 0),
(-1, 0)
];
private static bool IsValid(Coord dimensions, Coord position) {
var (width, height) = dimensions;
var (x, y) = position;
return y >= 0 && y < height && x >= 0 && x < width;
}
public int[][] HighestPeak(int[][] isWater) {
var (width, height) = (isWater[0].Length, isWater.Length);
var map = new int[height][];
for (var y = 0; y < height; ++y) {
map[y] = new int[width];
Array.Fill(map[y], UNSET);
}
var q = new Queue<Coord>();
for (var y = 0; y < height; ++y) {
for (var x = 0; x < width; ++x) {
if (isWater[y][x] != 1) {
continue;
}
q.Enqueue((x, y));
map[y][x] = 0;
}
}
var nextHeight = 1;
for (var n = q.Count; n > 0; ++nextHeight, n = q.Count) {
for (var i = 0; i < n; ++i) {
var (x, y) = q.Dequeue();
foreach (var (dx, dy) in DIRECTIONS) {
var nx = x + dx;
var ny = y + dy;
if (!IsValid((width, height), (nx, ny)) || map[ny][nx] != -1) {
continue;
}
map[ny][nx] = nextHeight;
q.Enqueue((nx, ny));
}
}
}
return map;
}
}