二维数组
定义一个二维数组
int[,] n=new int[几个一维数组,数组中的个数];
例:
int [,] n=new int [4,2]; 可以理解为4个一维数组,每个数组重包含2个元素。
int [,] n=new int [4,2]{{3,8},{1,2},{2,9},{5,7}}
取值则是:
int i=n[4,2]
i=7; //第四个数组的第二位 7;
int a=n[3,1]
a=2; //第三个数组的第二位 1;
我们可以利用二维数组来构建一个走迷宫或者推箱子地图来加深对二位数组的理解,
例,走迷宫
static void Main(string[] args)
{
int x, y, i, j, r;
x = 3; y = 3;r=0;
int[,] map = new int[10, 10]
{
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,1,1,1,0,1,0,1},
{1,0,0,2,0,1,1,4,1,1},
{1,0,0,1,0,1,1,0,1,1},
{1,0,0,1,0,0,0,0,1,1},
{1,0,0,1,0,1,1,1,1,1},
{1,0,0,1,0,1,0,0,0,1},
{1,0,0,1,0,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1},
}; //地图
while (true)
{
ConsoleKeyInfo d = Console.ReadKey(); //激活光标 ↑ ← ↓ →;
if (d.Key.ToString() == "RightArrow")
{ if(map[y,x+1]==0)
{
r = map[y, x]; //如果向右移动一格为0,那么值交换;
map[y, x] = map[y, x + 1];
map[y, x + 1] = r;
x++;
}
if (map[y, x + 1] ==4&&map[y,y+2]==0)
{
r = map[y, x];
map[y, x] = map[y, x + 2];
map[y, x + 1] = r;
x++;
r = map[y, x];
map[y, x] = map[y, x + 1];
map[y, x + 1] = r;
x++;
}
}
if (d.Key.ToString() == "DownArrow")
{
r = map[y, x];
map[y, x] = map[y + 1, x];
map[y + 1, x] = r;
y++;
}
if (d.Key.ToString() == "UpArrow")
{
r = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = r;
y--;
}
if (d.Key.ToString() == "LeftArrow")
{
r = map[y, x];
map[y, x] = map[y, x - 1];
map[y, x - 1] = r;
x--;
}
Console.Clear(); //清屏
for (i = 0; i < 10; i++) //打印地图
{
for (j = 0; j < 10; j++)
{
if (map[i, j] == 1)
{
Console.Write("■");
}
else if (map[i, j] == 0)
{
Console.Write(" ");
}
else if (map[i, j] == 2)
{
Console.Write("♀");
}
else if (map[i, j] == 4)
{
Console.Write("□");
}
else
{
break;
}
}
Console.WriteLine();
}
多讲无益,自己理解,方法很多。