💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 给定一个 n x n 方阵,求出大小为 k x k 的所有子方和 > 原文: [https://www.geeksforgeeks.org/given-n-x-n-square-matrix-find-sum-sub-squares-size-k-x-k/](https://www.geeksforgeeks.org/given-n-x-n-square-matrix-find-sum-sub-squares-size-k-x-k/) 给定一个 n x n 的正方形矩阵,求出所有大小为 k x k 的子正方形的和,其中 k 小于或等于 n。 **示例**: ``` Input: n = 5, k = 3 arr[][] = { {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; Output: 18 18 18 27 27 27 36 36 36 Input: n = 3, k = 2 arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, }; Output: 12 16 24 28 ``` **简单解决方案**是所有可能子正方形的一个接一个拾取起点(最左上角)。 选取起点后,从选取的起点开始计算子平方和。 以下是该想法的实现。 ## C++ ```cpp // A simple C++ program to find sum of all subsquares of size k x k #include <iostream> using namespace std; // Size of given matrix #define n 5 // A simple function to find sum of all sub-squares of size k x k // in a given square matrix of size n x n void printSumSimple(int mat[][n], int k) {    // k must be smaller than or equal to n    if (k > n) return;    // row number of first cell in current sub-square of size k x k    for (int i=0; i<n-k+1; i++)    {       // column of first cell in current sub-square of size k x k       for (int j=0; j<n-k+1; j++)       {           // Calculate and print sum of current sub-square           int sum = 0;           for (int p=i; p<k+i; p++)              for (int q=j; q<k+j; q++)                  sum += mat[p][q];            cout << sum << "  ";       }       // Line separator for sub-squares starting with next row       cout << endl;    } } // Driver program to test above function int main() {     int mat[n][n] = {{1, 1, 1, 1, 1},                      {2, 2, 2, 2, 2},                      {3, 3, 3, 3, 3},                      {4, 4, 4, 4, 4},                      {5, 5, 5, 5, 5},                     };     int k = 3;     printSumSimple(mat, k);     return 0; } ```