3546. Equal Sum Grid Partition I

This commit is contained in:
2026-03-25 12:43:02 +03:00
parent a3131bf6d0
commit d99b7d18e3
4 changed files with 103 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
public class Solution
{
struct SumInfo
{
public long Left;
public long Right;
public long Value;
}
public bool CanPartitionGrid(int[][] grid)
{
var height = grid.Length;
var width = grid[0].Length;
var colSums = new SumInfo[width];
var rowSums = new SumInfo[height];
for (var i = 0; i < height; i++)
{
for (var j = 0; j < grid[i].Length; j++)
{
colSums[j].Value += grid[i][j];
rowSums[i].Value += grid[i][j];
}
rowSums[i].Left = rowSums[i].Value;
if (i > 0)
rowSums[i].Left += rowSums[i - 1].Left;
}
for (var i = height - 1; i >= 0; i--)
{
rowSums[i].Right = rowSums[i].Value;
if (i < height - 1)
rowSums[i].Right += rowSums[i + 1].Right;
}
for (var j = 0; j < width; j++)
{
colSums[j].Left = colSums[j].Value;
if (j > 0)
colSums[j].Left += colSums[j - 1].Left;
}
for (var j = width - 1; j >= 0; j--)
{
colSums[j].Right = colSums[j].Value;
if (j < width - 1)
colSums[j].Right += colSums[j + 1].Right;
}
return rowSums.Any(row => Math.Abs(row.Left - row.Right) == row.Value) || colSums.Any(col => Math.Abs(col.Left - col.Right) == col.Value);
}
}