螺旋矩阵

题目信息

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:


matrix3_4.jpg

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

解题思路

  1. 暴力破解:
  2. 无效操作分析:
  3. 优化方法:
  4. 考虑边界
  5. 编码实现

代码

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        // 判断矩阵非空
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }

        // 获取循环数量
        int rows = matrix.length, columns = matrix[0].length;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom){
            // 上
            for (int column = left; column <= right; column++) {
                result.add(matrix[top][column]);
            }
            // 右
            for (int row = top + 1; row <= bottom; row++) {
                result.add(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                // 下
                for (int column = right - 1; column > left; column--) {
                    result.add(matrix[bottom][column]);
                }
                // 左
                for (int row = bottom; row > top; row--) {
                    result.add(matrix[row][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return result;
    }
}

题目来源:力扣(LeetCode)
题目链接:https://leetcode-cn.com/problems/spiral-matrix

商业转载请联系官方授权,非商业转载请注明出处。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 链接:https://leetcode-cn.com/problems/spiral-matrix[https:/...
    Comeon已被注册阅读 535评论 0 0
  • 题目信息 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正...
    Ziv_紫藤花开阅读 231评论 0 1
  • 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素 https://l...
    Shimmer_阅读 184评论 0 1
  • 题目:给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示...
    minningl阅读 155评论 0 0
  • 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。示例 1:...
    啊啊啊哼哼哼阅读 256评论 0 0