自己感觉建立转向标示比较容易不过也可以用递归
public class Demo{
private int[,] _SpiralMatrix;
private int _N;
public SpiralMatrix(int n)
{
_SpiralMatrix = new int[n, n];
_N = n;
}
/// <summary>
/// 递归算法
/// </summary>
/// <param name="start">start:矩阵开始的位置,如为0表示矩阵[0,0]元素</param>
/// <param name="num">矩阵的维数</param>
/// <param name="begin">起始数字</param>
public void Computer(int start,int num,int begin)
{
if (start == num)//输入为偶数时
{
return;
}
else if (start == num - 1)//输入为奇数时
{
_SpiralMatrix[start, num - 1] = begin;
return;
}
else
{
for (int i = start; i < num; i++)
{
_SpiralMatrix[start,i] = begin;
begin++;
}
for (int j = start + 1; j < num; j++)
{
_SpiralMatrix[j, num - 1] = begin;
begin++;
}
for (int k = num - 2; k >= start; k--)
{
_SpiralMatrix[num-1, k] = begin;
begin++;
}
for (int l = num - 2; l >= start+1; l--)
{
_SpiralMatrix[l, start] = begin;
begin++;
}
Computer(start + 1, num - 1, begin);
}
}
/// <summary>
/// 字符串化,方便对象输出
/// </summary>
/// <returns>字符串后的矩阵</returns>
public string ToString()
{
string temp="";
for(int i=0;i<_N;i++)
{
for(int j=0;j<_N;j++)
{
temp+=_SpiralMatrix[i,j]+" ";
}
temp+="\r\n";
}
return temp;
}
|