力扣 – 剑指 Offer 29. 顺时针打印矩阵

题目

剑指 Offer 29. 顺时针打印矩阵

思路1

  • 其实就是按照理解题目的意思一步步从外层到内层打印出来,同时将一个外层分成四个部分分步打印
  • 可以用一个变量count来维护当前打印的第几层
  • 判断打印结束了的条件是:count*2<column && count*2<row
  • 但是要注意的是边界条件的判断,可能最里面的一层不一定要四边全部都打印出来的情况记得判断

代码

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) {
            return new int[0];
        }

        int column = matrix[0].length;
        int row = matrix.length;
        //
        int[] res = new int[column * row];
        // 写入到res数组的指针
        int position = 0;
        // 代表的是第几遍循环
        int count = 0;

        while (count*2 < column && count*2 < row) {
            int endColumn = column - 1 - count;
            int endRow = row - 1 - count;

            // 打印上方
            // 只有这个不用判断,因为是最先打印的这个
            // 如果最内圈只有一行,那么其他三个方向就都不要打印了,所以其他三个方向要判断
            for (int i = count; i <= endColumn; i++) {
                res[position++] = matrix[count][i];
            }

            // 打印右侧
            if (count < endRow) {
                for (int i = count+1; i <= endRow; i++) {
                    res[position++] = matrix[i][endColumn];
                }
            }

            // 打印下方
            if (count < endColumn && count < endRow) {
                for (int i = endColumn-1; i >= count; i--) {
                    res[position++] = matrix[endRow][i];
                }
            }

            // 打印左侧
            if (count < endColumn && count < endRow) {
                for (int i = endRow-1; i > count; i--) {
                    res[position++] = matrix[i][count];
                }
            }

            count++;
        } 

        return res;
    }
}

复杂度分析

  • 时间复杂度:\(O(M*N)\)
  • 空间复杂度:\(O(1)\)