仓库源文站点原文


title: '算法:顺时针打印矩阵' cover: https://img.paulzzh.com/touhou/random?28 categories: 算法题目 date: 1996-07-27 08:00:00 toc: true

tags: [算法题目, 数组]

<br/>

<!--more-->

顺时针打印矩阵

顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字

例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.


分析

四个方向:

建立四个方向的index: left = 0, up = 0, down = row - 1, right = col - 1;

然后小心修改即可


代码

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return new ArrayList<>();

        int row = matrix.length, col = matrix[0].length;
        ArrayList<Integer> res = new ArrayList<>(row * col + 1);
        int left = 0, up = 0, down = row - 1, right = col - 1;
        while (left <= right && up <= down) {
            // left -> right
            for (int i = left; i <= right; i++) res.add(matrix[up][i]);
            // up -> down
            for (int i = up + 1; i <= down; ++i) res.add(matrix[i][right]);
            // right -> left
            if (up != down) {
                for (int i = right - 1; i >= left; --i) res.add(matrix[down][i]);
            }
            // down -> up
            if (left != right) {
                for (int i = down - 1; i > up; --i) res.add(matrix[i][left]);
            }
            left++;
            up++;
            down--;
            right--;
        }
        return res;
    }
}