<p><font face="仿宋">定义了NxN的二维数组,数组元素(整数)通过键盘输入,请编写程序,求出数组周边元素的和值,并输出。(2<=N<=100)</font><br/></p><p><font face="仿宋"><br/></font></p><p><font face="仿宋">输入格式:</font></p><p>第1行:输入N。其中2<=N<=100<br/>第2到N+1行,每行输入N的元素,元素之间用两个空格分隔。</p><p><br/></p><p>输出格
代码:
C++:
cpp
#include<iostream>
using namespace std;
const int N = 0x3f3f;
class Solution {
public:
int SumNum(int arr[], int n) {
int res = 0;
for (int i = 1; i <= n * n; i++) {
if (i < n) {
res += arr[i];
}
else if (i % n == 0 && i < n * n) {
res += arr[i];
res += arr[i + 1];
}
else if (i > n * (n - 1) + 1) {
res += arr[i];
}
}
return res;
}
};
int main() {
int arr[N];
int n;
cin >> n;
for (int i = 1; i <= n * n; i++) {
int num;
cin >> num;
arr[i] = num;
}
Solution solution = Solution();
int res = solution.SumNum(arr, n);
cout << res << endl;
return 0;
}
Python:
python
class Solution:
def SumNum(self, arr, n):
res = 0
for i in range(1, n * n + 1, 1):
if i < n:
res += arr[i]
elif i % n == 0 and i <= n * (n - 1) + 1:
res += arr[i]
res += arr[i + 1]
elif i > n * (n - 1) + 1:
res += arr[i]
return res
def main():
solution = Solution()
n = int(input())
arr = [0] * 0x3f3f
num = input().split()
for i in range(0, n * n, 1):
arr[i + 1] = int(num[i])
res = solution.SumNum(arr, n)
print(res)
if __name__=="__main__":
main()
Java:
java
package com.my.gududu;
import java.util.*;
class Solution {
int SumNum(int arr[], int n) {
int res = 0;
for (int i = 1; i <= n * n; i++) {
if (i < n) {
res += arr[i];
}
else if (i % n == 0 && i <= n * (n - 1)) {
res += arr[i];
res += arr[i + 1];
}
else if (i > n * (n - 1) + 1) {
res += arr[i];
}
}
return res;
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int arr[] = new int[0x3f3f];
for (int i = 1; i <= n * n; i++) {
int num = input.nextInt();
arr[i] = num;
}
Solution solution = new Solution();
int res = solution.SumNum(arr, n);
System.out.println(res);
}
}