题目
生成螺旋矩阵
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 ]
]
思路
递归实现
code
public class Solution {
private int[,] matrix;
private int elen;
public int[,] GenerateMatrix(int n)
{
matrix = new int[n, n];
elen = 0; //element count
spiral(0, n-1, n-1, 0);
return matrix;
}
private void spiral(int top, int right, int bottom, int left)
{
if (top > bottom || left > right) return;
//add first row
for (int j = left; j <= right; j++)
matrix[top, j] = ++elen;
//add last column
for (int i = top + 1; i <= bottom; i++)
matrix[i, right] = ++elen;
//add last row
for (int j = right - 1; j >= left && top != bottom; j--)
matrix[bottom, j] = ++elen;
//add first column
for (int i = bottom - 1; i > top && left != right; i--)
matrix[i, left] = ++elen;
spiral(top + 1, right - 1, bottom - 1, left + 1);
}
}