054 螺旋矩阵

题目

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

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

示例 2:

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

示例 3:

输入:
[
  [1]
]
输出: [1]

示例 4:

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

实现

  • 状态:通过
  • 22 / 22 个通过测试用例
  • 执行用时: 348 ms, 在所有 C# 提交中击败了 85.53% 的用户
  • 内存消耗: 28.9 MB, 在所有 C# 提交中击败了 5.26% 的用户
public class Solution
{
    public IList<int> SpiralOrder(int[][] matrix)
    {
        IList<int> result = new List<int>();
        if (matrix == null || matrix.Length == 0)
            return result;

        int start = 0;
        int end1 = matrix[start].Length - 1 - start;
        int end2 = matrix.Length - 1 - start;

        // 只有横着的情况
        if (start == end2)
        {
            LeftToRight(start, end1, start, matrix, result);
            return result;
        }
        //只有竖着的情况
        if (start == end1)
        {
            TopToBottom(start, end2, start, matrix, result);
            return result;
        }

        while (start < end1 && start < end2)
        {
            LeftToRight(start, end1, start, matrix, result);
            TopToBottom(start + 1, end2, end1, matrix, result);
            RightToLeft(end1 - 1, start, end2, matrix, result);
            BottomToTop(end2 - 1, start + 1, start, matrix, result);
            start++;
            end1 = matrix[start].Length - 1 - start;
            end2 = matrix.Length - 1 - start;
        }
        // 只剩下横着的情况
        if (start == end2)
        {
            LeftToRight(start, end1, start, matrix, result);
        }
        else if (start == end1)
        {
            //只剩下竖着的情况
            TopToBottom(start, end2, start, matrix, result);
        }
        return result;
    }

    private void LeftToRight(int start, int end, int rowIndex, int[][] matrix, IList<int> lst)
    {
        for (int i = start; i <= end; i++)
        {
            lst.Add(matrix[rowIndex][i]);
        }
    }

    private void TopToBottom(int start, int end, int colIndex, int[][] matrix, IList<int> lst)
    {
        for (int i = start; i <= end; i++)
        {
            lst.Add(matrix[i][colIndex]);
        }
    }

    private void RightToLeft(int start, int end, int rowIndex, int[][] matrix, IList<int> lst)
    {
        for (int i = start; i >= end; i--)
        {
            lst.Add(matrix[rowIndex][i]);
        }
    }

    private void BottomToTop(int start, int end, int colIndex, int[][] matrix, IList<int> lst)
    {
        for (int i = start; i >= end; i--)
        {
            lst.Add(matrix[i][colIndex]);
        }
    }
}
浙ICP备19012682号