美文网首页
LeetCode每日一题:spiral matrix i

LeetCode每日一题:spiral matrix i

作者: yoshino | 来源:发表于2017-06-07 10:06 被阅读24次

问题描述

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return[1,2,3,6,9,8,7,4,5].

问题分析

不需要什么算法,螺旋打印即可。

代码实现

public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();
        if (matrix.length == 0) return res;
        int m = matrix.length, n = matrix[0].length;
        // 计算圈数
        int lvl = (Math.min(m, n) + 1) / 2;
        for (int i = 0; i < lvl; i++) {
            int lastRow = m - i - 1;
            int lastCol = n - i - 1;
            if (i == lastRow) {
                for (int j = i; j <= lastCol; j++) {
                    res.add(matrix[i][j]);
                }
            } else if (i == lastCol) {
                for (int j = i; j <= lastRow; j++) {
                    res.add(matrix[j][i]);
                }
            } else {
                for (int j = i; j < lastCol; j++) {
                    res.add(matrix[i][j]);
                }
                for (int j = i; j < lastRow; j++) {
                    res.add(matrix[j][lastCol]);
                }
                for (int j = lastCol; j > i; j--) {
                    res.add(matrix[lastRow][j]);
                }
                for (int j = lastRow; j > i; j--) {
                    res.add(matrix[j][i]);
                }
            }
        }
        return res;
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:spiral matrix i

      本文链接:https://www.haomeiwen.com/subject/hgsofxtx.html