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

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

题目

链接

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

问题描述

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

示例

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

思路

直接模拟,首先y++,然后x++,然后y--,然后x--,设置边界值和tag控制方向。

复杂度分析

时间复杂度 O(mn)
空间复杂度 O(mn)

代码

Java

    public int[] spiralOrder(int[][] matrix) {
        int maxX = matrix[0].length;
        int maxY = matrix.length;
        int[] ans = new int[maxX * maxY];
        int up = 0, right = maxX - 1, left = 0, down = maxY - 1;
        int i = 0, j = 0, count = 1;
        int tag = 2;
        //右下左上
        ans[0] = matrix[0][0];
        while (count < maxX * maxY) {
            if (tag == 1) {
                if (i > up) {
                    i--;
                    ans[count++] = matrix[i][j];
                } else if (i == up) {
                    tag = 2;
                    left++;

                }
            } else if (tag == 2) {
                if (j < right) {
                    j++;
                    ans[count++] = matrix[i][j];
                } else if (j == right) {
                    tag = 3;
                    up++;
                }
            } else if (tag == 3) {
                if (i < down) {
                    i++;
                    ans[count++] = matrix[i][j];
                } else if (i == down) {
                    tag = 4;
                    right--;
                }
            } else if (tag == 4) {
                if (j > left) {
                    j--;
                    ans[count++] = matrix[i][j];
                } else if (j == left) {
                    tag = 1;
                    down--;
                }
            }
        }
        return ans;
    }
posted @ 2020-02-29 13:57  cheng102e  阅读(81)  评论(0编辑  收藏  举报