題目英文
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. “數值分析”類算法