逆时针打印矩阵

public class PrintMatrix {

    public static void main(String[] args) {

        int[][] p = {/** m ↓*/{1, 15, 14, 13,12},
                     /**   ↓*/{2, 16, 21, 20,11},
                     /**   ↓*/{3, 17, 18, 19,10},
                     /** n ↓*/{4, 5, 6, 7,9}};
                               /** k → j*/
        int direction = -1;
        int m = 0, n = 3;
        int k = 0, j = 4;

        //向下后k+1
        //向右后n-1
        //向上后j-1
        //向左后m+1
        //m=n&&k=j 结束
        while (true) {
            direction = (direction + 1) % 4;
            switch (direction) {
                case 0://↓
                    for (int i = m; i <= n; i++) {
                        System.out.print(p[i][k] + " ");
                    }
                    k++;
                    break;
                case 1://→
                    for (int i = k; i <= j; i++) {
                        System.out.print(p[n][i] + " ");
                    }
                    n--;
                    break;
                case 2://↑
                    for (int i = n; i >= m; i--) {
                        System.out.print(p[i][j] + " ");
                    }
                    j--;
                    break;
                case 3://←
                    for (int i = j; i >= k; i--) {
                        System.out.print(p[m][i] + " ");
                    }
                    m++;
                    break;
            }
            if (m == n && k == j) {
                break;
            }
        }

    }

}

你可能感兴趣的:(逆时针打印矩阵)