奇数平方的九宫格
private void btnTest_Click(object sender, EventArgs e)
{
int num = (int)numericUpDown1.Value;
int[,] arrData = new int[num, num];
int halfNum = num / 2;
int minNum = (num * num + 1) / 2;
for (int i = 0; i < num; i++)
{
arrData[i, i] = halfNum + minNum - i;
}
arrData[1, 0] = halfNum + minNum + 1;
int x = 0;
int y = 0;
for (int i = 0; i < num * num; i++)
{
if (i == 0)
{
arrData[0, halfNum] = 1;
x = 0;
y = halfNum;
continue;
}
if (i >= (minNum - halfNum) && i <= (minNum + halfNum))
{
x = 1;
y = 0;
continue;
}
if (x == 0)
{
if (arrData[num - 1, y - 1] == 0)
{
arrData[num - 1, y - 1] = i + 1;
x = num - 1;
y = y - 1;
continue;
}
}
else if (y == 0)
{
if (x > 0)
{
if (arrData[x - 1, num - 1] == 0)
{
x = x - 1;
y = num - 1;
arrData[x, y] = i + 1;
continue;
}
}
else
{
x = x + 1;
y = 0;
arrData[x, 0] = i + 1;
continue;
}
}
else
{
if (arrData[x - 1, y - 1] != 0)
{
x = x + 1;
arrData[x, y] = i + 1;
}
else
{
x = x - 1;
y = y - 1;
arrData[x, y] = i + 1;
}
}
}
string str = "";
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
str += FormatStr(arrData[i, j], (num * num).ToString().Length) + " ";
}
str += "\r\n";
str += "\r\n";
}
textBox1.Text = str;
}
string FormatStr(int num, int length)
{
string str = num.ToString();
int l = str.Length;
for (int i = l; i < length; i++)
{
str = " " + str;
}
return str;
}
6 1 8
7 5 3
2 9 4
以此类推的宫格