From 2e4f1e770b6e2945d9d4e4012185c323d0845fe3 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 11 Aug 2024 21:50:02 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB1568.=20Minimum=20Number=20of?= =?UTF-8?q?=20Days=20to=20Disconnect=20Island=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...mum-number-of-days-to-disconnect-island.cs | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 cs/minimum-number-of-days-to-disconnect-island.cs diff --git a/cs/minimum-number-of-days-to-disconnect-island.cs b/cs/minimum-number-of-days-to-disconnect-island.cs new file mode 100644 index 0000000..818f602 --- /dev/null +++ b/cs/minimum-number-of-days-to-disconnect-island.cs @@ -0,0 +1,87 @@ +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 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 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(); + 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; + } +}