題目概要:

Ex :

5 3 2 7 9
1 7 4 2 4
5 3 2 4 6
1 3 4 5 1
1 4 5 6 3

 

計算出(各邊裡數字的總和):

1 .5+3+2+7+9+1+4+5+6+1+1+1+3=63

2. 7+4+2+3+4+3+4+5=32

3. 2

解題方向:

最外圍總和-裡面總和。 Ex 如上表 紅字-(藍字+黑字)

程式碼:

//Java
import java.util.Scanner;
class uva11470{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n;
int cases=1;
while(sc.hasNextInt() && (n=sc.nextInt())!=0){
//初始化陣列。
int arr[][]=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
arr[i][j]=sc.nextInt();
}
}
int s=0; //最小邊界。
int e=n; //最大邊界
System.out.print("Case "+cases+":");
while(s<=e){
int out=0,in=0;
//最外圍總和。
for(int i=s;i<e;i++){
for(int j=s;j<e;j++){
out=out+arr[i][j];
}
}
//內圈總和。
for(int i=s+1;i<e-1;i++){
for(int j=s+1;j<e-1;j++){
in=in+arr[i][j];
}
}
// Output
if((out-in)!=0) System.out.print(" "+(out-in));
s++;
e--;
}
System.out.println("");
cases++;
}
}
}
view raw uva11470.java hosted with ❤ by GitHub

arrow
arrow
    文章標籤
    Java
    全站熱搜
    創作者介紹
    創作者 a7069810 的頭像
    a7069810

    紀錄自己的程式人生

    a7069810 發表在 痞客邦 留言(0) 人氣()