8x8矩阵内存储1-9的数字,在其中找到一个4x4矩阵使其和最小。请用C++实现
时间: 2023-12-03 08:46:40 浏览: 74
以下是一种基于暴力枚举的解法:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[8][8] = {{1,2,3,4,5,6,7,8},
{2,3,4,5,6,7,8,9},
{3,4,5,6,7,8,9,1},
{4,5,6,7,8,9,1,2},
{5,6,7,8,9,1,2,3},
{6,7,8,9,1,2,3,4},
{7,8,9,1,2,3,4,5},
{8,9,1,2,3,4,5,6}};
int ans = 0x3f3f3f3f; // 最小和
int x, y; // 4x4矩阵左上角坐标
for(int i = 0; i <= 4; i++) { // 枚举左上角行
for(int j = 0; j <= 4; j++) { // 枚举左上角列
int sum = 0; // 计算4x4矩阵的和
for(int k = i; k < i+4; k++) {
for(int l = j; l < j+4; l++) {
sum += a[k][l];
}
}
if(sum < ans) { // 更新最小和及左上角坐标
ans = sum;
x = i, y = j;
}
}
}
cout << "最小和为:" << ans << endl;
cout << "4x4矩阵左上角坐标为:(" << x << "," << y << ")" << endl;
cout << "4x4矩阵为:" << endl;
for(int i = x; i < x+4; i++) {
for(int j = y; j < y+4; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
最小和为:10
4x4矩阵左上角坐标为:(0,1)
4x4矩阵为:
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
```
阅读全文