题目英文
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. “数组”类算法
- LeetCode实战:三数之和
- LeetCode实战:最接近的三数之和
- LeetCode实战:求众数
- LeetCode实战:缺失的第一个正数
- LeetCode实战:快乐数
- LeetCode实战:寻找两个有序数组的中位数
- LeetCode实战:盛最多水的容器
- LeetCode实战:删除排序数组中的重复项
- LeetCode实战:搜索旋转排序数组
- LeetCode实战:螺旋矩阵
2. “链表”类算法
- LeetCode实战:两数相加
- LeetCode实战:删除链表的倒数第N个节点
- LeetCode实战:合并两个有序链表
- LeetCode实战:合并K个排序链表
- LeetCode实战:两两交换链表中的节点
- LeetCode实战:旋转链表
- LeetCode实战:环形链表
3. “栈”类算法
4. “队列”类算法
5. “递归”类算法
6. “字符串”类算法
7. “树”类算法
8. “哈希”类算法
9. “搜索”类算法
10. “动态规划”类算法
11. “回溯”类算法
11. “数值分析”类算法