mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 09:59:41 +01:00
88 lines
2.5 KiB
C#
88 lines
2.5 KiB
C#
|
public class Solution {
|
||
|
record Position(int x, int y) {
|
||
|
public bool InBounds(int width, int height)
|
||
|
=> y >= 0 && y < height && x >= 0 && x < width;
|
||
|
|
||
|
public static IEnumerable<Position> Grid(int width, int height) {
|
||
|
for (var y = 0; y < height; ++y) {
|
||
|
for (var x = 0; x < width; ++x) {
|
||
|
yield return new(x, y);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static Position operator +(Position lhs, Position rhs)
|
||
|
=> new(lhs.x + rhs.x, lhs.y + rhs.y);
|
||
|
}
|
||
|
|
||
|
private static readonly int WATER = 0;
|
||
|
private static readonly int ISLAND = 1;
|
||
|
private static readonly List<Position> DIRECTIONS = [
|
||
|
new Position(0, 1),
|
||
|
new Position(0, -1),
|
||
|
new Position(1, 0),
|
||
|
new Position(-1, 0),
|
||
|
];
|
||
|
|
||
|
private void Explore(int[][] grid, bool[,] visited, Position cell) {
|
||
|
var (width, height) = (grid[0].Length, grid.Length);
|
||
|
bool toVisit(Position p) => p.InBounds(width, height) && grid[p.y][p.x] == ISLAND && !visited[p.y, p.x];
|
||
|
|
||
|
var q = new Queue<Position>();
|
||
|
q.Enqueue(cell);
|
||
|
visited[cell.y, cell.x] = true;
|
||
|
|
||
|
while (q.TryDequeue(out var p)) {
|
||
|
foreach (var direction in DIRECTIONS) {
|
||
|
var next = p + direction;
|
||
|
if (toVisit(next)) {
|
||
|
q.Enqueue(next);
|
||
|
visited[next.y, next.x] = true;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private int CountIslands(int[][] grid) {
|
||
|
var (width, height) = (grid[0].Length, grid.Length);
|
||
|
|
||
|
var visited = new bool[height, width];
|
||
|
|
||
|
var islands = 0;
|
||
|
foreach (var cell in Position.Grid(width, height)) {
|
||
|
if (!visited[cell.y, cell.x] && grid[cell.y][cell.x] == ISLAND) {
|
||
|
Explore(grid, visited, cell);
|
||
|
++islands;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return islands;
|
||
|
}
|
||
|
|
||
|
public int MinDays(int[][] grid) {
|
||
|
var (width, height) = (grid[0].Length, grid.Length);
|
||
|
var islands = CountIslands(grid);
|
||
|
|
||
|
if (islands != 1) {
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
foreach (var p in Position.Grid(width, height)) {
|
||
|
if (grid[p.y][p.x] == WATER) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
grid[p.y][p.x] = WATER;
|
||
|
islands = CountIslands(grid);
|
||
|
|
||
|
if (islands != 1) {
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
grid[p.y][p.x] = ISLAND;
|
||
|
}
|
||
|
|
||
|
return 2;
|
||
|
}
|
||
|
}
|