题目
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
标签
Array
难度
中等
分析
题目意思是给定一个整形n,创建一个旋转的矩阵,由1-n²的数字填充。
解题思路是,按照以下顺序遍历数组,直到循环结束
1. 从colBegin到colEnd遍历,rowBegin++
2. 从rowBegin到rowEnd遍历,colEnd–
3. 从colEnd到colBegin遍历,rowEnd–
4. 从rowEnd到rowBegin遍历,colBegin++
C代码实现
int** generateMatrix(int n) {
int i=0, num=1;
int rowBegin=0, rowEnd= n-1;
int colBegin=0, colEnd=n-1;
int **matrix= (int **)malloc(n*sizeof(int *));
for(i=0;i<n;i++)
{
matrix[i]=(int *)malloc(n*sizeof(int));
memset(matrix[i], 0, sizeof(int)*n);
}
while(rowBegin<=rowEnd && colBegin<=colEnd)
{
for(i=colBegin; i<=colEnd; i++)
{
matrix[rowBegin][i] = num++;
//printf("111 matrix[%d][%d] : %d\n", rowBegin, i, matrix[rowBegin][i]);
}
rowBegin++;
for(i=rowBegin; i<=rowEnd; i++)
{
matrix[i][colEnd] = num++;
//printf("222 matrix[%d][%d] : %d\n", i, colEnd, matrix[i][colEnd]);
}
colEnd--;
if(rowBegin<=rowEnd)
{
for(i=colEnd; i>=colBegin; i--)
{
matrix[rowEnd][i] = num++;
//printf("333 matrix[%d][%d] : %d\n", rowEnd, i, matrix[rowEnd][i]);
}
}
rowEnd--;
if(colBegin<=colEnd)
{
for(i=rowEnd; i>=rowBegin; i--)
{
matrix[i][colBegin] = num++;
//printf("444 matrix[%d][%d] : %d\n", i, colBegin, matrix[i][colBegin]);
}
}
colBegin++;
}
return matrix;
}