- 题号:59
- 难度:中等
- https://leetcode-cn.com/problems/spiral-matrix-ii/
给定一个正整数 n,生成一个包含 1 到 n 2 n^2 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
C# 语言
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++;
}
}
}
Python 语言
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
self.count = 1
self.matrix = [[0 for i in range(n)] for i in range(n)]
start, end1, end2 = 0, n - 1, n - 1
while start < end1 and start < end2:
self.LeftToRight(start, end1, start)
self.TopToBottom(start + 1, end2, end1)
self.RightToLeft(end1 - 1, start, end2)
self.BottomToTop(end2 - 1, start + 1, start)
start += 1
end1 = n - 1 - start
end2 = n - 1 - start
if n % 2 == 1:
self.matrix[start][start] = self.count
return self.matrix
def LeftToRight(self, start, end, rowIndex):
for i in range(start, end + 1):
self.matrix[rowIndex][i] = self.count
self.count += 1
def TopToBottom(self, start, end, colIndex):
for i in range(start, end + 1):
self.matrix[i][colIndex] = self.count
self.count += 1
def RightToLeft(self, start, end, rowIndex):
for i in range(start, end - 1, -1):
self.matrix[rowIndex][i] = self.count
self.count += 1
def BottomToTop(self, start, end, colIndex):
for i in range(start, end - 1, -1):
self.matrix[i][colIndex] = self.count
self.count += 1