i=1时,打印
1 2 3
8 9 4
7 6 5i=2时,打印
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
i=3时,打印
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9当输入任意大于1的整数时候,比如i=10,打印相应的图形。
1 2 3
8 9 4
7 6 5i=2时,打印
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
i=3时,打印
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9当输入任意大于1的整数时候,比如i=10,打印相应的图形。
相当于n*n个格子,从0,0的位置顺时针由外圈向内圈逐个打印
n = i+2;
static void Main(string[] args)
{
PrintBox(1);
Console.WriteLine("---------------");
PrintBox(2);
Console.WriteLine("---------------");
PrintBox(3);
}
public static void PrintBox(int row)
{
row = row + 2;
int[,] array = new int[row, row];
int index = 1;
int j = 0, k = 0; int right = row - 1, left = 0, bottom = row - 1, top = 1;
for (int i = 0; i < row / 2 + row % 2; i++)
{
while (k <= right)
array[j, k++] = index++;
k--;
j++;
while (j <= bottom)
array[j++, k] = index++;
j--;
k--;
while (k >= left)
array[j, k--] = index++;
k++;
j--;
while (j >= top)
array[j--, k] = index++;
j++;
k++;
right--;
left++;
bottom--;
top++;
}
for (int a = 0; a < row; a++)
{
for (int b = 0; b < row; b++)
Console.Write(array[a, b].ToString().PadLeft(2, '0') + " ");
Console.WriteLine();
}
}
{
Program.Print(10);
Console.ReadLine();
}
static void Print(int N)
{
bool xZheng = true ,xFu = false,yZheng = false ,yFu = false;
int K = N+2,i,j;
int[,] xx = new int[K,K];
for ( i = 0; i < K; i++)
{
for ( j = 0; j < K; j++)
xx[i, j] = 0;
}
i = 0; j = 0;
for (int h = 1; h <= K * K; h++)
{
xx[i, j] = h;
//表示上一步是→方向正走》》》》
if (xZheng)
{
if ((j + 1) < K)
{
if ((xx[i, j + 1] == 0))
{
j = j + 1;
continue;//继续走下去
}
else
{
xZheng = false;
yZheng = true;
i = i + 1;
}
}
else
{
//表示走到了头,方向↓往走
xZheng = false;
yZheng = true;
i = i + 1;
}
}
else if (yZheng)
{
if ((i + 1) < K)
{
if ((xx[i + 1, j] == 0))
{
i = i + 1;
continue;//继续走下去
}
else
{
//走到了头,需要往←方向走
yZheng = false;
xFu = true;
j = j - 1;
}
}
else
{
//走到了头,需要往←方向走
yZheng = false;
xFu = true;
j = j - 1;
}
}
else if (xFu)
{
if (j > 0)
{
if (xx[i, j - 1] == 0)
{
j = j - 1;
}
else
{
//走到了头,需要往↑方向走
yFu = true;
xFu = false;
i = i - 1;
}
}
else
{
//走到了头,需要往↑方向走
yFu = true;
xFu = false;
i = i - 1;
}
continue;
}
else if (yFu)
{
if (i > 0)
{
if (xx[i - 1, j] == 0)
{
i = i - 1;
}
else
{
//走到了头,需要往→方向走
yFu = false;
xZheng = true;
j = j + 1;
}
}
else
{
//走到了头,需要往→方向走
yFu = false;
xZheng = true;
j = j + 1;
}
}
} for (i = 0; i < K; i++)
{
for(j=0;j<K;j++)
{
Console.Write("{0:D4} ", xx[i, j]);
}
Console.Write("\n");
}
}
你比我快一倍啊,呵呵!
代码也写得比我好,佩服。