文章506
标签266
分类65

算法:顺时针打印矩阵


顺时针打印矩阵

顺时针打印矩阵

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

例如,如果输入如下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;
    }
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/1996/07/27/算法-顺时针打印矩阵/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可