package Day8_06; /*讀入兩個整數m,n,輸出一個m行n列的矩陣,這個矩陣是1~m*n這些自然數按照右、下、左、上螺旋填入的結果。 * 例如讀入數字4,5,則輸出結果為: * 1 2 3 4 5 * 14 15 16 17 6 * 13 20 19 18 7 * 12 11 10 9 8 */ import java.util.Scanner; public class LuoXuan { public static void main(String[] args) { System.out.println("Input:"); Scanner s = new Scanner(System.in); int m = s.nextInt(); int n = s.nextInt(); int[][] arr = new int[m][n]; int x; //橫坐標 int y; //豎坐標 int z = 1; //給數組元素賦的值 int c = 0; while(true){ if(z > m * n) break; // 打印第(c)行 for(x=c,y=c; y<n-c; y++){ arr[x][y] = z; z++; } // 打印第(n-c)列 for(x=c+1,y=n-1-c; x<m-c; x++){ arr[x][y] = z; z++; } // 打印第(m-1-c)行 for(x=m-1-c,y=n-2-c; y>=c; y--){ arr[x][y] = z; z++; } // 打印第(c)列 for(x=m-2-c,y=c; x>c; x--){ arr[x][y] = z; z++; } c++; } for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ System.out.print(arr[i][j] + "\t"); } System.out.println(); } } }

