cs: add «1765. Map of Highest Peak»
URL: https://leetcode.com/problems/map-of-highest-peak/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
c6bacfc1d9
commit
854ec005a6
1 changed files with 59 additions and 0 deletions
59
cs/map-of-highest-peak.cs
Normal file
59
cs/map-of-highest-peak.cs
Normal file
|
@ -0,0 +1,59 @@
|
|||
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;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue