题目英文
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. “栈”类算法
- LeetCode实战:有效的括号
- LeetCode实战:最长有效括号
- LeetCode实战:逆波兰表达式求值
4. “队列”类算法
- LeetCode实战:设计循环双端队列
- LeetCode实战:滑动窗口最大值
- LeetCode实战:整数反转
- LeetCode实战:字符串转换整数 (atoi)
5. “递归”类算法
- LeetCode实战:爬楼梯
6. “字符串”类算法
- LeetCode实战:反转字符串
- LeetCode实战:翻转字符串里的单词
- LeetCode实战:最长公共前缀
- LeetCode实战:字符串相加
- LeetCode实战:字符串相乘
7. “树”类算法
- LeetCode实战:相同的树
- LeetCode实战:对称二叉树
- LeetCode实战:二叉树的最大深度
- LeetCode实战:将有序数组转换为二叉搜索树
8. “哈希”类算法
- LeetCode实战:两数之和
9. “搜索”类算法
- LeetCode实战:搜索二维矩阵
10. “动态规划”类算法
- LeetCode实战:最长回文子串
- LeetCode实战:最大子序和
11. “回溯”类算法
- LeetCode实战:全排列
11. “数值分析”类算法
- LeetCode实战:回文数
- LeetCode实战:x 的平方根