| | 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.CountSquareSubmatricesWithAllOnes; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountSquareSubmatricesWithAllOnesBruteForce : ICountSquareSubmatricesWithAllOnes |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m * n * min(m, n)^2) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="matrix"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int CountSquares(int[][] matrix) |
| 2 | 24 | | { |
| 2 | 25 | | var m = matrix.Length; |
| 2 | 26 | | var n = matrix[0].Length; |
| | 27 | |
|
| 2 | 28 | | var sideLength = Math.Min(m, n); |
| | 29 | |
|
| 2 | 30 | | var count = 0; |
| | 31 | |
|
| 16 | 32 | | for (var k = 1; k <= sideLength; k++) |
| 6 | 33 | | { |
| 6 | 34 | | var targetSum = k * k; |
| | 35 | |
|
| 36 | 36 | | for (var i = 0; i <= m - k; i++) |
| 12 | 37 | | { |
| 92 | 38 | | for (var j = 0; j <= n - k; j++) |
| 34 | 39 | | { |
| 34 | 40 | | var sum = 0; |
| | 41 | |
|
| 168 | 42 | | for (var l = i; l < i + k; l++) |
| 50 | 43 | | { |
| 276 | 44 | | for (var o = j; o < j + k; o++) |
| 88 | 45 | | { |
| 88 | 46 | | sum += matrix[l][o]; |
| 88 | 47 | | } |
| 50 | 48 | | } |
| | 49 | |
|
| 34 | 50 | | if (sum == targetSum) |
| 22 | 51 | | { |
| 22 | 52 | | count++; |
| 22 | 53 | | } |
| 34 | 54 | | } |
| 12 | 55 | | } |
| 6 | 56 | | } |
| | 57 | |
|
| 2 | 58 | | return count; |
| 2 | 59 | | } |
| | 60 | | } |