螺旋形打印矩阵

package 矩阵1;

public class JuZheng {
    public static void main(String args[]) {

        int n = 5;
        int m = 0;
        int k = 0;
        int[][] a = new int[n][n];
        if (n % 2 == 0) {
            m = n;
        } else {
            m = n / 2 + 1;
        }
        for (int i = 0; i < m; i++) {
            for (int j = i; j < n - i; j++) {
                k++;
                a[i][j] = k;
            }
            for (int j = i + 1; j < n - i; j++) {
                k++;
                a[j][n - 1 - i] = k;
            }
            for (int j = n - i - 2; j >= i; j--) {
                k++;
                a[n - i - 1][j] = k;
            }
            for (int j = n - i - 2; j >= i + 1; j--) {
                k++;
                a[j][i] = k;
            }

        }
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length; j++) {
                if (a[i][j] < 5) {
                    System.out.print(" ");
                }

                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
}
 1  2  3  4 5 
16 17 18 19 6 
15 24 25 20 7 
14 23 22 21 8 
13 12 11 10 9 

 

posted @ 2015-08-19 15:39  大数据从业者FelixZh  阅读(270)  评论(0编辑  收藏  举报