Created
December 11, 2025 21:25
-
-
Save michael-duren/06195206afc99958458df41d47361a1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class NumberOfIslands | |
| { | |
| public static int NumIslands(char[][] grid) | |
| { | |
| int numberOfIslands = 0; | |
| for (int i = 0; i < grid.Length; i++) | |
| { | |
| for (int j = 0; j < grid[i].Length; j++) | |
| { | |
| if (grid[i][j] == '1') | |
| { | |
| numberOfIslands++; | |
| Traverse(grid, new Coords(x: j, y: i)); | |
| } | |
| } | |
| } | |
| return numberOfIslands; | |
| } | |
| private readonly struct Coords(int x, int y) | |
| { | |
| public readonly int X = x; | |
| public readonly int Y = y; | |
| } | |
| enum Direction | |
| { | |
| Up, | |
| Right, | |
| Down, | |
| Left, | |
| } | |
| private static Coords GetDirection(Coords coordinates, Direction direction) => | |
| direction switch | |
| { | |
| Direction.Up => new Coords(coordinates.X, coordinates.Y - 1), | |
| Direction.Right => new Coords(coordinates.X + 1, coordinates.Y), | |
| Direction.Down => new Coords(coordinates.X, coordinates.Y - 1), | |
| Direction.Left => new Coords(coordinates.X - 1, coordinates.Y), | |
| _ => throw new NotImplementedException(), | |
| }; | |
| private static void Traverse(char[][] grid, Coords coordinates) | |
| { | |
| if ( | |
| coordinates.X < 0 | |
| || coordinates.X >= grid[0].Length | |
| || coordinates.Y < 0 | |
| || coordinates.Y >= grid.Length | |
| ) | |
| { | |
| return; | |
| } | |
| // if we're not an island or we've seen this return buddy | |
| if (grid[coordinates.Y][coordinates.X] != '1') | |
| return; | |
| grid[coordinates.Y][coordinates.X] = 's'; | |
| foreach (var direction in Enum.GetValues<Direction>()) | |
| { | |
| Traverse(grid, GetDirection(coordinates, direction)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment