Sword to Offer-29 顺时针打印矩阵 ❀

  • 题目描述:
    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

  • 例如:如果输入如下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

解题思路:

1、用四个指针记录下目前还未遍历的最大最小行数列数;
未被遍历的最小行数大于最大行数,或者最小列数大于最大列数的时候,终止循环;
(即,循环条件为同时满足两组min<=max

2、每一次循环转一个环形读取数据,需注意边界的取值:
(1)向右的遍历可从min遍历到max,向下的遍历可从min+1遍历到max,向左的遍历可以从max-1遍历到min,向上的遍历可以从max-1遍历到min+1
(2)每完成一次环状遍历后,缩小范围,min+1max-1

问题图解:

AC代码:

// Print Maxtrix's Elements Clockwise

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        //用于返回的ArrayList
        ArrayList<Integer> ret = new ArrayList<>();
        int rowMin = 0, rowMax = matrix.length - 1;
        int colMin = 0, colMax = matrix[0].length - 1;
        while (rowMin<=rowMax && colMin<=colMax) {
            for (int i=colMin; i<=colMax; i++) {
                ret.add(matrix[rowMin][i]);
            }
            for (int i=rowMin+1; i<=rowMax; i++) {
                ret.add(matrix[i][colMax]);
            }
            if (rowMin != rowMax) {
                for (int i=colMax-1; i>=colMin; i--) {
                    ret.add(matrix[rowMax][i]);
                }
            }
            if (colMin != colMax) {
                for (int i=rowMax-1; i>rowMin; i--) {
                    ret.add(matrix[i][colMin]);
                }
            }
            rowMin++;
            rowMax--;
            colMin++;
            colMax--;
        }
        return ret;
    }
}

补充说明:

Comments


yangzail © 2020. All rights reserved.

Powered by Hydejack v8.5.2