1 条题解
-
0
练62.3 学习效率
解题思路
对每个中心格枚举3×3内所有合法坐标并求和,含中心本人的勤奋值。
正确性说明
依题目给出的对应关系逐项处理,位置与原输入保持明确对应。每一步完成当前项的全部贡献,结束后得到所有位置或字符的目标结果。
易错点
区别于只求邻居和的题,这里中心必须计入;不要原地修改输入数组。
复杂度
时间O(n²),空间O(n²)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<vector<int>> a(n, vector<int>(n)); for (auto &r : a) for (int &x : r) cin >> x; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) { int x = i + dx, y = j + dy; if (x >= 0 && x < n && y >= 0 && y < n) sum += a[x][y]; } if (j) cout << " "; cout << sum; } cout << "\n"; } return 0; }
- 1