3546. Equal Sum Grid Partition I
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>_3546._Equal_Sum_Grid_Partition_I</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
29
3546. Equal Sum Grid Partition I/Program.cs
Normal file
29
3546. Equal Sum Grid Partition I/Program.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
var sol = new Solution();
|
||||
|
||||
var cases = new (int[][] grid, bool expected, string name)[]
|
||||
{
|
||||
(
|
||||
new[]
|
||||
{
|
||||
new[] { 1, 4 },
|
||||
new[] { 2, 3 }
|
||||
},
|
||||
true,
|
||||
"Example 1"
|
||||
),
|
||||
(
|
||||
new[]
|
||||
{
|
||||
new[] { 1, 3 },
|
||||
new[] { 2, 4 }
|
||||
},
|
||||
false,
|
||||
"Example 2"
|
||||
)
|
||||
};
|
||||
|
||||
foreach (var (grid, expected, name) in cases)
|
||||
{
|
||||
var actual = sol.CanPartitionGrid(grid);
|
||||
Console.WriteLine($"{name}: {actual} (expected: {expected})");
|
||||
}
|
||||
49
3546. Equal Sum Grid Partition I/Solution.cs
Normal file
49
3546. Equal Sum Grid Partition I/Solution.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user