| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.EqualSumGridPartition1; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class EqualSumGridPartition1PrecomputedPrefixSum : IEqualSumGridPartition1 |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(m * n) |
| | | 19 | | /// Space complexity - O(m + n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="grid"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public bool CanPartitionGrid(int[][] grid) |
| | 2 | 24 | | { |
| | 2 | 25 | | var m = grid.Length; |
| | 2 | 26 | | var n = grid[0].Length; |
| | | 27 | | |
| | 2 | 28 | | Span<long> rowSums = stackalloc long[m]; |
| | 2 | 29 | | Span<long> columnSums = stackalloc long[n]; |
| | | 30 | | |
| | 2 | 31 | | long totalSum = 0; |
| | | 32 | | |
| | 12 | 33 | | for (var i = 0; i < m; i++) |
| | 4 | 34 | | { |
| | 4 | 35 | | var row = grid[i]; |
| | | 36 | | |
| | 24 | 37 | | for (var j = 0; j < n; j++) |
| | 8 | 38 | | { |
| | 8 | 39 | | var value = row[j]; |
| | | 40 | | |
| | 8 | 41 | | rowSums[i] += value; |
| | 8 | 42 | | columnSums[j] += value; |
| | 8 | 43 | | totalSum += value; |
| | 8 | 44 | | } |
| | 4 | 45 | | } |
| | | 46 | | |
| | 2 | 47 | | if (totalSum % 2 != 0) |
| | 0 | 48 | | { |
| | 0 | 49 | | return false; |
| | | 50 | | } |
| | | 51 | | |
| | 2 | 52 | | var targetSum = totalSum / 2; |
| | | 53 | | |
| | 2 | 54 | | long rowSum = 0; |
| | | 55 | | |
| | 6 | 56 | | for (var i = 0; i < m - 1; i++) |
| | 2 | 57 | | { |
| | 2 | 58 | | rowSum += rowSums[i]; |
| | | 59 | | |
| | 2 | 60 | | if (rowSum == targetSum) |
| | 1 | 61 | | { |
| | 1 | 62 | | return true; |
| | | 63 | | } |
| | 1 | 64 | | } |
| | | 65 | | |
| | 1 | 66 | | long columnSum = 0; |
| | | 67 | | |
| | 4 | 68 | | for (var j = 0; j < n - 1; j++) |
| | 1 | 69 | | { |
| | 1 | 70 | | columnSum += columnSums[j]; |
| | | 71 | | |
| | 1 | 72 | | if (columnSum == targetSum) |
| | 0 | 73 | | { |
| | 0 | 74 | | return true; |
| | | 75 | | } |
| | 1 | 76 | | } |
| | | 77 | | |
| | 1 | 78 | | return false; |
| | 2 | 79 | | } |
| | | 80 | | } |