LeetCode实战:螺旋矩阵 II

题目英文

Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题目中文

给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

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

算法实现

public class Solution
{
    public int[][] GenerateMatrix(int n)
    {
        int[][] matrix = new int[n][];
        for (int i = 0; i < n; i++)
        {
            matrix[i] = new int[n];
        }

        int start = 0;//起始位置
        int end1 = n - 1;//最左边位置
        int end2 = n - 1;//最下边位置
        int count = 1;

        while (start < end1 && start < end2)
        {
            LeftToRight(start, end1, start, matrix, ref count);
            TopToBottom(start + 1, end2, end1, matrix, ref count);
            RightToLeft(end1 - 1, start, end2, matrix, ref count);
            BottomToTop(end2 - 1, start + 1, start, matrix, ref count);
            start++;
            end1 = n - 1 - start;
            end2 = n - 1 - start;
        }
        if (n%2 == 1)
        {
            matrix[start][start] = count;
        }
        return matrix;
    }

    private void LeftToRight(int start, int end, int rowIndex, int[][] matrix, ref int from)
    {
        for (int i = start; i <= end; i++)
        {
            matrix[rowIndex][i] = from;
            from++;
        }
    }

    private void TopToBottom(int start, int end, int colIndex, int[][] matrix, ref int from)
    {
        for (int i = start; i <= end; i++)
        {
            matrix[i][colIndex] = from;
            from++;
        }
    }

    private void RightToLeft(int start, int end, int rowIndex, int[][] matrix, ref int from)
    {
        for (int i = start; i >= end; i--)
        {
            matrix[rowIndex][i] = from;
            from++;
        }
    }

    private void BottomToTop(int start, int end, int colIndex, int[][] matrix, ref int from)
    {
        for (int i = start; i >= end; i--)
        {
            matrix[i][colIndex] = from;
            from++;
        }
    }

}

实验结果

  • 状态:通过
  • 20 / 20 个通过测试用例
  • 执行用时: 296 ms, 在所有 C# 提交中击败了 97.67% 的用户
  • 内存消耗: 25 MB, 在所有 C# 提交中击败了 11.11% 的用户

提交结果


相关图文

1. “数组”类算法

2. “链表”类算法

3. “栈”类算法

4. “队列”类算法

5. “递归”类算法

6. “字符串”类算法

7. “树”类算法

8. “哈希”类算法

9. “搜索”类算法

10. “动态规划”类算法

11. “回溯”类算法

11. “数值分析”类算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章