C#反螺旋矩阵(数组)方阵
C#反螺旋矩阵(数组)方阵
using System;
using System.Collections.Generic; using System.Text;
namespace ConsoleApplication1 {
class Program
{
static void Main(string[] args)
{
int n = 0; //螺旋方阵的阶数
bool inputIsRight = false; //输入是否正确
string response;
do
{
do
{
Console.Write("请输入螺旋方阵的阶数(大于零的整数):");
try
{
string iStr = Console.ReadLine();
n = Convert.ToInt16(iStr);
if (n < 1)
inputIsRight = true;
else
inputIsRight = false;
Console.Write("\n");
}
catch
{
Console.Write("\n");
Console.Write("输入有误," + "请重新输入螺旋方阵的阶数(大于零的整数)~\n");
Console.Write("\n");
}
} while (inputIsRight);
int[,] iArray = new int[n, n];
int rc = 3, iValue = 1; //rc=0:竖着往下走给数组赋值,rc=1:横着往右走给数组赋值,
//rc=2:竖着往上走给数组赋值,rc=3:横着往左走给数组赋值
int i = 0, j = n;
int maxRow = n, maxCol = n, minRow = -1, minCol
= -1;
do
{
switch (rc)
{
case 3:
j--;
while (j > minCol)
{
iArray[i, j] = iValue++;
j--;
}
j++; ;
minRow++;
rc = 0;
break;
case 2:
i--;
while (i > minRow)
{
iArray[i, j] = iValue++;
i--;
}
i++;
maxCol--;
rc = 3;
break;
case 1:
j++;
while (j < maxCol)
{
iArray[i, j] = iValue++;
j++;
}
j--; ;
maxRow--;
rc = 2;
break;
case 0:
i++; //防止如iVarray[0,1]这样的拐点重复赋值
while (i < maxRow)
{
iArray[i, j] = iValue++;
i++;
}
i--;//一步完后i=maxRow(溢出),所以要i--
minCol++;
rc = 1;
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();
}
Console.WriteLine("是否继续(Y/N):");
response = Console.ReadLine();
while ((response != "Y") && (response != "y") && (response != "N") && (response != "n"))
{
Console.WriteLine("输入错误");
Console.Write("是否继续(Y/N):");
response = Console.ReadLine();
}
} while ((response == "Y") || (response == "y"));
Console.Write("\n");
Console.Write("感谢使用此程序~");
Console.Read();
}
}
}
本文档为【C#反螺旋矩阵(数组)方阵】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。