| | 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.CountSubIslands; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountSubIslandsDepthFirstSearch : ICountSubIslands |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m * n) |
| | 19 | | /// Space complexity - O(m * n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="grid1"></param> |
| | 22 | | /// <param name="grid2"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int CountSubIslands(int[][] grid1, int[][] grid2) |
| 2 | 25 | | { |
| 2 | 26 | | var count = 0; |
| | 27 | |
|
| 24 | 28 | | for (var i = 0; i < grid1.Length; i++) |
| 10 | 29 | | { |
| 120 | 30 | | for (var j = 0; j < grid1[i].Length; j++) |
| 50 | 31 | | { |
| 50 | 32 | | if (grid2[i][j] != 1 || grid1[i][j] != 1) |
| 43 | 33 | | { |
| 43 | 34 | | continue; |
| | 35 | | } |
| | 36 | |
|
| 7 | 37 | | if (GetIsSubIsland(grid1, grid2, i, j)) |
| 5 | 38 | | { |
| 5 | 39 | | count++; |
| 5 | 40 | | } |
| 7 | 41 | | } |
| 10 | 42 | | } |
| | 43 | |
|
| 2 | 44 | | return count; |
| 2 | 45 | | } |
| | 46 | |
|
| | 47 | | private static bool GetIsSubIsland(int[][] grid1, int[][] grid2, int i, int j) |
| 95 | 48 | | { |
| 95 | 49 | | if (i < 0 || j < 0 || i >= grid1.Length || j >= grid1[i].Length || grid2[i][j] == 0) |
| 73 | 50 | | { |
| 73 | 51 | | return true; |
| | 52 | | } |
| | 53 | |
|
| 22 | 54 | | grid2[i][j] = 0; |
| | 55 | |
|
| 22 | 56 | | var isSubIsland = grid1[i][j] == 1; |
| | 57 | |
|
| 22 | 58 | | isSubIsland &= GetIsSubIsland(grid1, grid2, i + 1, j); |
| 22 | 59 | | isSubIsland &= GetIsSubIsland(grid1, grid2, i - 1, j); |
| 22 | 60 | | isSubIsland &= GetIsSubIsland(grid1, grid2, i, j + 1); |
| 22 | 61 | | isSubIsland &= GetIsSubIsland(grid1, grid2, i, j - 1); |
| | 62 | |
|
| 22 | 63 | | return isSubIsland; |
| 95 | 64 | | } |
| | 65 | | } |