1
0
bastien.monsarrat 6 жил өмнө
parent
commit
26810042d9
1 өөрчлөгдсөн 20 нэмэгдсэн , 11 устгасан
  1. 20 11
      D11.2/Program.cs

+ 20 - 11
D11.2/Program.cs

@@ -11,6 +11,7 @@ namespace D11._2
 
             const int length = 300;
             var grid = new int[length, length];
+            var summedGrid = new int[length, length];
 
             for (int x = 1; x <= length; ++x)
             {
@@ -29,28 +30,36 @@ namespace D11._2
             int maxTotal = 0;
             (int x, int y, int g)? maxCoordinates = null;
 
-            for (var g = 0; g < length; ++g)
+            for (var size = 0; size < length; ++size)
             {
-                for (int x = 1; x <= length -g + 1; ++x)
-                    for (int y = 1; y <= length -g + 1; ++y)
+                for (int x = 0; x < length - size; ++x)
+                    for (int y = 0; y < length - size; ++y)
                     {
-                        
-                        int total = 0;
-                        for (int j = 0; j < g; ++j)
-                            for (int i = 0; i < g; ++i)
-                            {
-                                total += grid[x - 1 + i, y - 1 + j];
-                            }
+                        int total = SumSquare(grid, summedGrid, size, x, y);
 
                         if (total > maxTotal)
                         {
                             maxTotal = total;
-                            maxCoordinates = (x, y, g);
+                            maxCoordinates = (x + 1, y + 1, size + 1);
                         }
                     }
             }
 
             Console.WriteLine($"The answer is : ({maxCoordinates.Value.x},{maxCoordinates.Value.y},{maxCoordinates.Value.g})");
         }
+
+        private static int SumSquare(int[,] grid, int[,] summedGrid, int size, int x, int y)
+        {
+            // summedGrid contains the sum previously calculated for size - 1
+            int total = summedGrid[x, y];
+
+            // new sum is obtained by taking the previous sum and adding the edges plus the corner
+            for (int i = 0; i < size; ++i)
+                total += grid[x + i, y + size] + grid[x + size, y + i];
+            total += grid[x + size, y + size];
+
+            summedGrid[x, y] = total;
+            return total;
+        }
     }
 }