【剑指offer-JZ29】顺时针打印矩阵

70 阅读1分钟
package cn.allan.y;

import java.util.ArrayList;

public class Solution {
    public static ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> a = new ArrayList<>();
        if (matrix.length == 0 || matrix[0].length == 0) return a;
        int i, left = 0, top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1;
        // 按照:向右->向下->向左->向上 的方向遍历。每次遇到边界就改变方向并且向内缩减一下当前运动所占据的方向(比如从左往右走到头了,就向内缩减一下top,让top+1)
        while (left <= right && top <= bottom) {
            // 从左往右
            for (i = left; i <= right; i++) a.add(matrix[top][i]);
            top++;
            // 从上往下
            for (i = top; i <= bottom; i++) a.add(matrix[i][right]);
            right--;
            // 因为while中的判断需要加等号,那么在奇数行或奇数列的时候就会重复计算最中间的行或列,所以在一侧遍历完后要及时的判断一下,指针是否重合了
            if (top - 1 == bottom || left == right + 1) break;  // 因为在前面top已经加过1,right也已经减过1了,所以这里要还原一下
            // 从右往左
            for (i = right; i >= left; i--) a.add(matrix[bottom][i]);
            bottom--;
            // 从下往上
            for (i = bottom; i >= top; i--) a.add(matrix[i][left]);
            left++;
        }
        return a;
    }


    public static void main(String[] args) {
        int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        System.out.println(printMatrix(a));
    }
}



题源:www.nowcoder.com/practice/9b…