二十:顺时针打印矩阵

题目

用螺旋的方式打印矩阵, 比如如下的矩阵
0 1 2 3
4 5 6 7
8 9 10 11
打印顺序为: 0 1 2 3 7 11 10 9 8 4 5 6

实现

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int[][] matrix = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrix[i][j] = in.nextInt();
            }
        }
        f(matrix);
    }
    
    public static void f(int[][] m) {
        //用两个点a和b,分别表示左上角的点和右下角的点,来控制转圈的打印顺序
        int ah = 0;
        int al = 0;
        int bh = m.length - 1;
        int bl = m[0].length - 1;
        while (ah <= bh && al <= bl) { //注意这里的条件,第二个条件不能少,比如说五行四列的情况
            printEdge(m, ah++, al++, bh--, bl--);
        }
    }
    
    public static void printEdge(int[][] m , int ah, int al, int bh, int bl) {
        //考虑只有一行的情况
        if (ah == bh) {
            while (al <= bl) {
                System.out.print(m[ah][al++] + " ");    
            }
        } else if (al == bl) { //考虑只有一列的情况下
            while (ah <= bh) {
                System.out.print(m[ah++][al] + " ");
            }
        } else { //正常情况下
            int curC = al;
            int curR = ah;
            //打印上面的行
            while (curC < bl) {
                System.out.print(m[curR][curC++] + " ");
            }
            //打印右面的列
            while (curR < bh) {
                System.out.print(m[curR++][curC] + " ");
            }
            //打印下面的行
            while (curC > al) {
                System.out.print(m[curR][curC--] + " ");
            }
            //打印左边的列
            while (curR > ah) {
                System.out.print(m[curR--][curC] + " ");
            }
        }
    }
    
}

你可能感兴趣的:(算法)