Description
You are given an m x n matrix grid of positive integers. Your task is to determine if it is possible to make either one horizontal or one vertical cut on the grid such that:
- Each of the two resulting sections formed by the cut is non-empty.
- The sum of the elements in both sections is equal.
Return true if such a partition exists; otherwise return false.
Example 1:
Input: grid = [[1,4],[2,3]]
Output: true
Explanation:


A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is true.
Example 2:
Input: grid = [[1,3],[2,4]]
Output: false
Explanation:
No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is false.
Constraints:
1 <= m == grid.length <= 1051 <= n == grid[i].length <= 1052 <= m * n <= 1051 <= grid[i][j] <= 105
Solutions
This sums the entire grid, confirms it's even, then iterates through rows and columns (excluding the last of each) to find a partition point where the running sum equals half the total.
/**
* @param {number[][]} grid
* @return {boolean}
*/
var canPartitionGrid = function(grid) {
const m = grid.length;
const n = grid[0].length;
let total = 0;
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
total += grid[row][col];
}
}
if (total & 1) {
return false;
}
const target = total / 2;
let sum = 0;
for (let row = 0; row < m - 1; row++) {
for (let col = 0; col < n; col++) {
sum += grid[row][col];
}
if (sum === target) {
return true;
}
}
sum = 0;
for (let col = 0; col < n - 1; col++) {
for (let row = 0; row < m; row++) {
sum += grid[row][col];
}
if (sum === target) {
return true;
}
}
return false;
};