Spiraly print n*n matrix.
Eg: [1,2,3,4]
[12,13,14,5]
[11,16,15,6]
[10,9,8,7]
Should print
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
螺旋输出n*n矩阵
分析:n*n矩阵可分为n-2层输出,每层按照顺时针方向输出,每层输出的开始元素下标为 A[i][i]
public class PrintMatrix { /** * question: * Spiraly print n*n matrix. Eg: [1,2,3,4] [12,13,14,5] [11,16,15,6] [10,9,8,7] Should print 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 */ public static void main(String[] args) { int[][] A = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; int[][] B ={{ 0, 1, 2, 3, 4}, {15, 16, 17, 18, 5}, {14, 23, 24, 19, 6}, {13, 22, 21, 20, 7}, {12, 11, 10, 9, 8}}; System.out.println(printMatrix(A)); System.out.println(printMatrix(B)); } public static String printMatrix(int[][] A){ StringBuffer sb = new StringBuffer(); int n = A.length; for(int i=0;i<n-2;i++){ for(int j=i;j<n-i-1;j++){ sb.append(String.valueOf(A[i][j])).append(" "); } for(int j=i;j<n-i-1;j++){ sb.append(String.valueOf(A[j][n-i-1])).append(" "); } for(int j=n-i-1;j>i;j--){ sb.append(String.valueOf(A[n-i-1][j])).append(" "); } for(int j=n-i-1;j>i;j--){ sb.append(String.valueOf(A[j][i])).append(" "); } } return sb.toString(); } }