111,126
社区成员
发帖
与我相关
我的任务
分享using System.Collections.Generic;
using System.Text;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[16, 16];//数组长度,必须相同且为偶数
int num = 1;//定义一个变量,用于自加,并且初始化的为1
int length = arr.GetLength(0) - 1;//获取数组的单维长度
int x = length;//循环控制变量
int id_1 = 0, id_2 = length;//数组下标控制变量
int temp = 0;//循环后的下标变量
while (x > 0)
{
for (int i1 = 0; i1 < x; i1++)//上
{
arr[id_1, i1+temp] = num++;//i1时动态下标
//Console.Write(temp+",");
}
for (int i2 = 0; i2 <x; i2++)//右
{
arr[i2 + temp, id_2] = num++;
}
for (int i3 = 0; i3 < x; i3++)//下
{
arr[id_2, length - i3 - temp] = num++;
}
for (int i4 = 0; i4 < x; i4++)//左
{
arr[length - i4 - temp, id_1] = num++;
}
temp++;
id_1++;
id_2--;
x = x - 2;
}
for (int i = 0; i < length + 1; i++)//输出
{
for (int n = 0; n < length + 1; n++)
{
Console.Write(" {0:d3} ", arr[i, n]);
}
Console.WriteLine();
}
}
}
}
class Program
{
static void Main(string[] args)
{
const int X = 10; const int Y = 10;
int[,] Nums = new int[X, Y];
int x = 0, y = 0, direction = 0;
Nums[0, 0] = 1; checkDirection(Nums, ref x, ref y, ref direction);
for (int i = 0; i < X; i++)
{
for (int j = 0; j < Y; j++)
{
Console.Write(Nums[i, j].ToString().PadLeft(4, ' '));
}
Console.Write("\n");
}
Console.Read();
}
/// <summary>
/// 在黑暗中摸索前进
/// </summary>
/// <param name="Nums">数组</param>
/// <param name="x">当前位置在数组的横坐标,一维</param>
/// <param name="y">当前位置在数组的纵坐标,二维</param>
/// <param name="value">当前位置的值</param>
/// <param name="direction">数字转的方向:0 前 y+,1 下 x+,2 后 y-,3 上 x-</param>
private static void checkDirection(int[,] Nums, ref int x, ref int y, ref int direction)
{
int curentValue = Nums[x, y];
Go(ref x, ref y, direction, true);
if (x < Nums.GetLowerBound(0) || x > Nums.GetUpperBound(0) || y < Nums.GetLowerBound(1) || y > Nums.GetUpperBound(1) || Nums[x, y] > 0)
{
Go(ref x, ref y, direction, false);
direction = (direction + 1) % 4;
Go(ref x, ref y, direction, true);
}
if (Nums[x, y] > 0) return;
Nums[x, y] = curentValue + 1; checkDirection(Nums, ref x, ref y, ref direction);
}
/// <summary>
/// 踏出一步。向前?后退?
/// </summary>
/// <param name="x">横坐标</param>
/// <param name="y">纵坐标</param>
/// <param name="direction">下一步枪口朝向</param>
/// <param name="IsForward">向前或后退</param>
private static void Go(ref int x, ref int y, int direction, bool IsForward)
{
if (IsForward)
{
if (direction == 0) y += 1;
else if (direction == 1) x += 1;
else if (direction == 2) y -= 1;
else if (direction == 3) x -= 1;
}
else
{
if (direction == 0) y -= 1;
else if (direction == 1) x -= 1;
else if (direction == 2) y += 1;
else if (direction == 3) x += 1;
}
}
}
要打印那种形式是可以,但是…要用二维数组,。。。于我而言,太难了…学习。。。
有意思…呵呵int[] arr = new int[10,10];
for(int i=0;i<10;i++)
{
for(int n=0;n<10;n++)
{
arr[i][n]="值";
}
}
int[] arr = new int[10,10];
for(int i=0;i<10;i++)
{
for(int n=0;n<10;n++)
{
arr[i][n]="值";
}
}