標籤:
問題:列印輸出逆時針螺旋矩陣,要求螺旋矩陣的階數由使用者輸入。例如 n=4時,輸出的螺旋矩陣如下:
下面給出My Code:
1 package org.warnier.zhang.exercises; 2 3 public class Convolution { 4 private int n; 5 private int[][] array; 6 private int number = 1; 7 8 public Convolution(int n) { 9 this.n = n;10 array = new int[n][n];11 init();12 }13 14 private void init() {15 for (int i = 0; i < n; i++) {16 for (int j = 0; j < n; j++) {17 array[i][j] = 0;18 }19 }20 }21 22 //逆時針方向迴旋;23 public void generateConvolutionNumber() {24 //處理迭代“內圈”數字輸出;25 int a = 0;26 int b = n -1 - a;27 while (b >= a) {28 //與正常的數組輸出方向一致螺旋輸出;29 for (int i = a; i <= b; i++) {30 for (int j = a; j <= b; j++) {31 if (i != b && j == a) {32 array[i][j] = number++;33 }34 if (i == b && j != b) {35 array[i][j] = number++;36 }37 }38 }39 40 //與正常的數組輸出方向相反螺旋輸出;41 for (int i = b; i >= a; i--) {42 for (int j = b; j >= a; j--) {43 if (i != a && j == b) {44 array[i][j] = number++;45 }46 if (i == a && j != a) {47 array[i][j] = number++;48 }49 }50 }51 52 a ++;53 b = n -1 - a;54 }55 56 //打個補丁:沒能解決n為奇數的情況!(沒有加上這句代碼,中間的空格輸出預設值0!)57 if(n % 2 != 0){58 array[n/2][n/2] = number;59 }60 }61 62 public void vprintf() {63 for (int i = 0; i < n; i++) {64 for (int j = 0; j < n; j++) {65 System.out.printf("%3d", array[i][j]);66 }67 System.out.println();68 }69 }70 71 }
簡要說明,a 和 b 的存在,是為瞭解決螺旋輸出內圈的數字;下面的是測試代碼:
1 package org.warnier.zhang.exercises; 2 3 public class ConvolutionTest { 4 5 public static void main(String[] args) { 6 Convolution convolution = new Convolution(5); 7 convolution.generateConvolutionNumber(); 8 convolution.vprintf(); 9 }10 11 }12 13 結果:14 1 16 15 14 1315 2 17 24 23 1216 3 18 25 22 1117 4 19 20 21 1018 5 6 7 8 9
這是我的解決方案,主要是將迴旋劃分為從上到下,從左至右,從下到上,從右至左的四個方向分別處理,要注意後兩個方向與正常的數組輸出方向相反。這道演算法題對學生黨來說有點壓力,但是掌握了能夠寫出好多好玩的東西,比如貪吃蛇。上面的演算法只是一種可能的實現,歡迎讀者貼上自己的代碼,交流交流!
演算法導論:列印迴旋數;