| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.NumberOfIslands; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class NumberOfIslandsIterative : INumberOfIslands |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * m) |
| | 19 | | /// Space complexity - O(n * m) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="grid"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int NumIslands(char[][] grid) |
| 2 | 24 | | { |
| 2 | 25 | | var num = 0; |
| | 26 | |
|
| 20 | 27 | | for (var i = 0; i < grid.Length; i++) |
| 8 | 28 | | { |
| 96 | 29 | | for (var j = 0; j < grid[i].Length; j++) |
| 40 | 30 | | { |
| 40 | 31 | | if (grid[i][j] != '1') |
| 36 | 32 | | { |
| 36 | 33 | | continue; |
| | 34 | | } |
| | 35 | |
|
| 4 | 36 | | num++; |
| | 37 | |
|
| 4 | 38 | | Find(grid, i, j); |
| 4 | 39 | | } |
| 8 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | return num; |
| 2 | 43 | | } |
| | 44 | |
|
| | 45 | | private static void Find(IReadOnlyList<char[]> grid, int i, int j) |
| 19 | 46 | | { |
| 19 | 47 | | if (i + 1 < grid.Count && grid[i + 1][j] == '1') |
| 5 | 48 | | { |
| 5 | 49 | | grid[i + 1][j] = '2'; |
| | 50 | |
|
| 5 | 51 | | Find(grid, i + 1, j); |
| 5 | 52 | | } |
| | 53 | |
|
| 19 | 54 | | if (i - 1 >= 0 && grid[i - 1][j] == '1') |
| 3 | 55 | | { |
| 3 | 56 | | grid[i - 1][j] = '2'; |
| | 57 | |
|
| 3 | 58 | | Find(grid, i - 1, j); |
| 3 | 59 | | } |
| | 60 | |
|
| 19 | 61 | | if (j + 1 < grid[i].Length && grid[i][j + 1] == '1') |
| 5 | 62 | | { |
| 5 | 63 | | grid[i][j + 1] = '2'; |
| | 64 | |
|
| 5 | 65 | | Find(grid, i, j + 1); |
| 5 | 66 | | } |
| | 67 | |
|
| 19 | 68 | | if (j - 1 >= 0 && grid[i][j - 1] == '1') |
| 2 | 69 | | { |
| 2 | 70 | | grid[i][j - 1] = '2'; |
| | 71 | |
|
| 2 | 72 | | Find(grid, i, j - 1); |
| 2 | 73 | | } |
| 19 | 74 | | } |
| | 75 | | } |