【剑指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]

数据范围:

0 <= matrix.length <= 100

0 <= matrix[i].length <= 100

示例1

输入:[[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]

示例2

输入:[[1,2,3,1],[4,5,6,1],[4,5,6,1]]

返回值:[1,2,3,1,1,1,6,5,4,4,5,6]

解答

源代码

import java.util.*;
import java.util.ArrayList;
public class Solution {
    public ArrayList printMatrix(int [][] matrix) {
        if (matrix == null) {
            return null;
        }

        ArrayList res = new ArrayList<>();
        int left = 0, right = matrix[0].length - 1;
        int up = 0, down = matrix.length - 1;

        while (left <= right && up <= down) {
            for (int i = left; i <= right; i++) {
                res.add(matrix[up][i]);
            }

            up++;
            if (up > down) {
                break;
            }

            for (int i = up; i <= down; i++) {
                res.add(matrix[i][right]);
            }

            right--;
            if (left > right) {
                break;
            }

            for (int i = right; i >= left; i--) {
                res.add(matrix[down][i]);
            }

            down--;
            if (up > down) {
                break;
            }

            for (int i = down; i >= up; i--) {
                res.add(matrix[i][left]);
            }

            left++;
            if (left > right) {
                break;
            }
       }

       return res;
    }
}

总结

设置好边界,每遍历完一列或一行都要对边界进行调整,并且调整后需要进行判断看边界是否相交了。

你可能感兴趣的:(剑指Offer,算法,java,矩阵)