leetcode
54. 螺旋矩阵

问题描述

LeetCode 54. 螺旋矩阵 (opens in a new tab),难度中等

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

示例 1

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

示例 2

输入: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]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

题解

题解:建议画图,判断边界条件,光在脑子里想可能有点乱。

Solution.java
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        int top = 0, bottom = matrix.length-1, left = 0, right = matrix[0].length-1;
        while (left <= right && top <= bottom) {
            // 模拟遍历最上面一行
            for (int j = left; j <= right; ++j) {
                ans.add(matrix[top][j]);
            }
            top++;
 
            // 模拟遍历最右侧一列
            for (int i = top; i <= bottom; ++i) {
                ans.add(matrix[i][right]);
            }
            right--;
 
            if (top <= bottom) {
                // 模拟遍历最下面一行
                for (int j = right; j >= left; j--) {
                    ans.add(matrix[bottom][j]);
                }
            }
            bottom--;
 
            if (left <= right) {
                // 模拟遍历最左侧一列
                for (int i = bottom; i >= top; i--) {
                    ans.add(matrix[i][left]);
                }
            }
            left++;
        }
        return ans;
    }
}