蛇形添数
在n*n的方阵填入1,2,3……n*n.最后形成蛇形。例如n=4时的方阵为:其中(n<=8)
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
源程序如下:
using System;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
int[,] snake=new int[9,9];
Console.Write("Input:");
int n = int.Parse(Console.ReadLine());
int x = 0;
int y = n-1;
snake[x, y] = 1;
int number=1;
while (number < n*n)
{
while(x+1<n)
{
if (snake[x + 1, y] == 0)
{
number++;
x++;
snake[x, y] = number;
}
else
{
break;
}
// Console.Write("向下[{0},{1}]:{2}", x, y, snake[x, y] + " ");
}
while (y > 0)
{
if (snake[x, y - 1] == 0)
{
number++;
y--;
snake[x, y] = number;
}
else
{
break;
}
//Console.Write("向左[{0},{1}]:{2}",x,y, snake[x, y] + " ");
}
while (x > 0)
{
if (snake[x - 1, y] == 0)
{
number++;
x--;
snake[x, y] = number;
}
else
{
break;
}
// Console.Write("向上[{0},{1}]:{2}", x, y, snake[x, y] + " ");
}
while (y < n)
{
if (snake[x, y + 1] == 0)
{
number++;
y++;
snake[x, y] = number;
}
else
{
break;
}
// Console.Write("向右[{0},{1}]:{2}", x, y, snake[x, y] + " ");
}
}
Console.WriteLine();
Console.WriteLine("输入结果:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(snake[i, j] + " ");
if ((j + 1) % n == 0)
{
Console.WriteLine();
}
}
}
Console.ReadKey();
}
}
}
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
int[,] snake=new int[9,9];
Console.Write("Input:");
int n = int.Parse(Console.ReadLine());
int x = 0;
int y = n-1;
snake[x, y] = 1;
int number=1;
while (number < n*n)
{
while(x+1<n)
{
if (snake[x + 1, y] == 0)
{
number++;
x++;
snake[x, y] = number;
}
else
{
break;
}
// Console.Write("向下[{0},{1}]:{2}", x, y, snake[x, y] + " ");
}
while (y > 0)
{
if (snake[x, y - 1] == 0)
{
number++;
y--;
snake[x, y] = number;
}
else
{
break;
}
//Console.Write("向左[{0},{1}]:{2}",x,y, snake[x, y] + " ");
}
while (x > 0)
{
if (snake[x - 1, y] == 0)
{
number++;
x--;
snake[x, y] = number;
}
else
{
break;
}
// Console.Write("向上[{0},{1}]:{2}", x, y, snake[x, y] + " ");
}
while (y < n)
{
if (snake[x, y + 1] == 0)
{
number++;
y++;
snake[x, y] = number;
}
else
{
break;
}
// Console.Write("向右[{0},{1}]:{2}", x, y, snake[x, y] + " ");
}
}
Console.WriteLine();
Console.WriteLine("输入结果:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(snake[i, j] + " ");
if ((j + 1) % n == 0)
{
Console.WriteLine();
}
}
}
Console.ReadKey();
}
}
}