奇数阶魔方算法
Code
static void Main(string[] args)
{
string flag = "y";
while (flag == "Y" || flag == "y")
{
Console.WriteLine("请输入一个奇数:");
string s = Console.ReadLine();
if (s.Length > 1)
return;
if (!char.IsNumber(s,0))
return;
int nn = Convert.ToInt32(s);
if (nn != 0 && nn / 2 != 0)
{
int[,] arryss = Demo(nn);
for (int i = 0; i < nn; i++)
{
for (int j = 0; j < nn; j++)
{
Console.Write(arryss[i, j] + "\t");
if ((j + 1) % nn == 0)
{
Console.Write("\n");
}
}
}
Console.WriteLine("=== 继续 请输入 Y 或 y ===");
flag = Console.ReadLine();
}
}
Console.WriteLine("……按任意键结束……");
Console.ReadLine();
}
private static int[,] Demo(int n)
{
int[,] arryInt = new int[n, n];
int i = 0; //X坐标
int j = n / 2; //Y坐标
arryInt[i, j] = 1;//给最中心的点赋值
for (int k = 2; k <= n * n; k++)
{
if (i >= 0 && i < n)
{
i--;
if (i < 0)
{
i = i + n;
}
}
if (j >= 0 && j < n)
{
j++;
if (j >= n)
{
j = j - n;
}
}
if (arryInt[i, j] != 0)//该数组的位置已经被占用
{
i = i + 2;
if (i >= n)
{
i = i - n;
}
j--;
if (j < 0)
{
j = j + n;
}
arryInt[i, j] = k;
}
else
{
arryInt[i, j] = k;
}
}
return arryInt;
}
static void Main(string[] args)
{
string flag = "y";
while (flag == "Y" || flag == "y")
{
Console.WriteLine("请输入一个奇数:");
string s = Console.ReadLine();
if (s.Length > 1)
return;
if (!char.IsNumber(s,0))
return;
int nn = Convert.ToInt32(s);
if (nn != 0 && nn / 2 != 0)
{
int[,] arryss = Demo(nn);
for (int i = 0; i < nn; i++)
{
for (int j = 0; j < nn; j++)
{
Console.Write(arryss[i, j] + "\t");
if ((j + 1) % nn == 0)
{
Console.Write("\n");
}
}
}
Console.WriteLine("=== 继续 请输入 Y 或 y ===");
flag = Console.ReadLine();
}
}
Console.WriteLine("……按任意键结束……");
Console.ReadLine();
}
private static int[,] Demo(int n)
{
int[,] arryInt = new int[n, n];
int i = 0; //X坐标
int j = n / 2; //Y坐标
arryInt[i, j] = 1;//给最中心的点赋值
for (int k = 2; k <= n * n; k++)
{
if (i >= 0 && i < n)
{
i--;
if (i < 0)
{
i = i + n;
}
}
if (j >= 0 && j < n)
{
j++;
if (j >= n)
{
j = j - n;
}
}
if (arryInt[i, j] != 0)//该数组的位置已经被占用
{
i = i + 2;
if (i >= n)
{
i = i - n;
}
j--;
if (j < 0)
{
j = j + n;
}
arryInt[i, j] = k;
}
else
{
arryInt[i, j] = k;
}
}
return arryInt;
}
每天进步一点点...