andy6804tw
2/21/2017 - 9:05 AM

## http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?id=3019 這題螺旋矩陣最直覺方法就是模擬，那如何做呢?首先不管順(逆)時鐘都有個規律，建議各位還是在紙上寫下每個位置的索引值如下: [0,0] [0

http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?id=3019

[0,0] [0,1] [0,2] [0,3] [1,0] [1,1] [1,2] [1,3] [2,0] [2,1] [2,2] [2,3] [3,0] [3,1] [3,2] [3,3]

``````import java.util.*;

public class Main {

public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str[] = scn.nextLine().split(",");
int n = Integer.parseInt(str[0]), index = Integer.parseInt(str[1]), count = 1, arr[][] = new int[n][n];
if (index == 1) {//順時鐘
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++)
arr[i][j] = count++;
for (int j = i; j < n - i - 1; j++)
arr[j][n - i - 1] = count++;
for (int j = n - i - 1; j > i; j--)
arr[n - i - 1][j] = count++;
for (int j = n - i - 1; j > i; j--)
arr[j][i] = count++;
}
} else {//逆時鐘
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++)
arr[j][i] = count++;
for (int j = i; j < n - i - 1; j++)
arr[n - 1 - i][j] = count++;
for (int j = n - i - 1; j > i; j--)
arr[j][n - i - 1] = count++;
for (int j = n - i - 1; j > i; j--)
arr[i][j] = count++;
}
}
if (n % 2 != 0)//遇到基數層要補上中心數
arr[n / 2][n / 2] = count;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%03d", arr[i][j]);
if (j != n - 1)
System.out.print(",");
}
System.out.println();
}
}
/*題目：[C_AR40-易] 螺旋矩陣
作者：1010
時間：西元 2017 年 2 月 */
}
``````