题解 | #顺时针打印矩阵#

顺时针打印矩阵

http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

顺时针打印矩阵


描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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

输入:[[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、搞清楚打几圈

  • 打一圈需要两层在这里插入图片描述

  • 打印几圈取决于行数(r)和列数(c)中小的那个,如(r<c):(r / 2)向上取整 在这里插入图片描述

2、定义边界 alt

3、过程

  • 从左到右,打印完后top++,消除该行

alt

  • 从上到下,打印完后right--,消除该列

alt

  • 从右到左,打印完后bottom--,消除该行

alt

  • 从下到上,打印完后left++,消除该列,第一圈完成

alt


import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {


        // 0、定义返回列表
        ArrayList<Integer> res = new ArrayList<>();

        // 1、判空
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }

        // 2、定义边界
        int top = 0;
        int bottom = matrix.length - 1; // 行
        int left = 0;
        int right = matrix[0].length-1; // 列

        // 3、进入循环,r 代表行  c 代表列
        while (true) {


            // 3.1 left 到 right  从左到右(行不变) 打印第一行
            for (int c = left; c <= right; c++) {
                // 存储遍历的结果
                res.add(matrix[top][c]);
            }

            // 向下靠近,打印完后消除当前top行,缩小边界值
            top++;
            // 越界判断
            if (top > bottom) {
                break;
            }

            // 3.2 right 到 bottom  从上到下(列不变)
            for (int r = top; r <= bottom; r++) {
                // 存储遍历的结果
                res.add(matrix[r][right]);
            }

            // 向左靠近,打印完后消除当前right行,缩小边界值
            right--;
            // 越界判断
            if (left > right) {
                break;
            }

            // 3.3 right 到 left  从右到左(行不变)
            for (int c = right; c >= left; c--) {
                // 存储遍历的结果
                res.add(matrix[bottom][c]);
            }

            // 向上靠近,打印完后消除当前bottom行,缩小边界值
            bottom--;
            if (top > bottom) {
                break;
            }

            // 3.4 bottom 到 top  从下到上(列不变)
            for (int r = bottom; r >= top; r--) {
                // 存储遍历的结果
                res.add(matrix[r][left]);
            }

            // 向右靠近,打印完后消除当前left行,缩小边界值
            left++;
            if (left > right) {
                break;
            }
        }


        return res;


    }
}

复杂度分析:

  • 时间复杂度:O(N)
  • 空间复杂度:O(N)
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务