| | 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.CountSubmatricesWithAllOnes; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountSubmatricesWithAllOnesVerticalHeights : ICountSubmatricesWithAllOnes |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m * n^2) |
| | 19 | | /// Space complexity - (n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="mat"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int NumSubmat(int[][] mat) |
| 2 | 24 | | { |
| 2 | 25 | | var m = mat.Length; |
| 2 | 26 | | var n = mat[0].Length; |
| | 27 | |
|
| 2 | 28 | | var heights = new int[n]; |
| | 29 | |
|
| 2 | 30 | | var result = 0; |
| | 31 | |
|
| 16 | 32 | | for (var i = 0; i < m; i++) |
| 6 | 33 | | { |
| 54 | 34 | | for (var j = 0; j < n; j++) |
| 21 | 35 | | { |
| 21 | 36 | | if (mat[i][j] == 0) |
| 7 | 37 | | { |
| 7 | 38 | | heights[j] = 0; |
| 7 | 39 | | } |
| | 40 | | else |
| 14 | 41 | | { |
| 14 | 42 | | heights[j]++; |
| 14 | 43 | | } |
| 21 | 44 | | } |
| | 45 | |
|
| 54 | 46 | | for (var j = 0; j < n; j++) |
| 21 | 47 | | { |
| 21 | 48 | | if (heights[j] == 0) |
| 7 | 49 | | { |
| 7 | 50 | | continue; |
| | 51 | | } |
| | 52 | |
|
| 14 | 53 | | var minHeight = heights[j]; |
| | 54 | |
|
| 74 | 55 | | for (var k = j; k >= 0 && minHeight > 0; k--) |
| 29 | 56 | | { |
| 29 | 57 | | if (heights[k] < minHeight) |
| 8 | 58 | | { |
| 8 | 59 | | minHeight = heights[k]; |
| 8 | 60 | | } |
| | 61 | |
|
| 29 | 62 | | if (minHeight == 0) |
| 6 | 63 | | { |
| 6 | 64 | | break; |
| | 65 | | } |
| | 66 | |
|
| 23 | 67 | | result += minHeight; |
| 23 | 68 | | } |
| 14 | 69 | | } |
| 6 | 70 | | } |
| | 71 | |
|
| 2 | 72 | | return result; |
| 2 | 73 | | } |
| | 74 | | } |