在网上找到一篇 LZ应该问之前自己搜一下
原址:http://hi.baidu.com/woiwojia/blog/item/ba397800a9f91d15738b6526.html
输出螺旋矩阵[c#]2008-03-18 22:52例如输出4*4的螺旋矩阵:
1
12
11
10
2
13
16
9
3
14
15
8
4
5
6
7
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int n = 0;//螺旋方阵的阶数
bool inputIsRight = false; //输入是否正确
do
{
Console.Write("请输入螺旋方阵的阶数(大于零的整数):");
try
{
string iStr = Console.ReadLine();
n = Convert.ToInt16(iStr);
if (n < 1)
inputIsRight = true;
else
inputIsRight = false;
}
catch
{
Console.Write("输入有误\n" + "请重新输入螺旋方阵的阶数(大于零的整数):");
}
} while (inputIsRight);
int [,]iArray = new int[n,n];
int rc = 0, iValue = 1;
//rc=0:竖着往下走给数组赋值,rc=1:横着往右走给数组赋值,
//rc=2:竖着往上走给数组赋值,rc=3:横着往左走给数组赋值
int i=-1,j=0;
int maxRow = n, maxCol = n, minRow = -1, minCol = -1;
do
{
switch (rc)
{
case 0:
i++; //防止如iVarray[0,1]这样的拐点重复赋值
while (i < maxRow )
{
iArray[i, j] = iValue++;
i++;
}
i--;//一步完后i=maxRow(溢出),所以要i--
minCol++;
rc = 1;
break;
case 1:
j++;
while (j < maxCol)
{
iArray[i, j] = iValue++;
j ++;
}
j--; ;
maxRow--;
rc = 2;
break;
case 2:
i--;
while (i > minRow)
{
iArray[i, j] = iValue++;
i--;
}
i++;
maxCol--;
rc = 3;
break;
case 3:
j--;
while (j >minCol)
{
iArray[i, j] = iValue++;
j--;
}
j++; ;
minRow++;
rc = 0;
break;
}
}while(iValue<=n*n);
int cout = 0;
foreach (int ii in iArray) //输出矩阵
{
if (ii < 10)
Console.Write(" " + ii.ToString() + " ");
else if (ii < 100)
Console.Write(" " + ii.ToString() + " ");
else
Console.Write(ii.ToString() + " ");
cout++;
if (cout % n == 0) Console.WriteLine();
}
}
}
}
[[it] 本帖最后由 乖老鼠 于 2009-7-22 11:35 编辑 [/it]]