【发布时间】:2017-07-22 10:05:34
【问题描述】:
我想要实现的是:
8 7 6 5 6 7 8
7 6 5 4 5 6 7
6 5 4 3 4 5 6
5 4 3 2 3 4 5
4 3 2 1 2 3 4
5 4 3 2 3 4 5
6 5 4 3 4 5 6
7 6 5 4 5 6 7
8 7 6 5 6 7 8
1 - 从给定坐标 (X;Y) 的起点
【问题讨论】:
我想要实现的是:
8 7 6 5 6 7 8
7 6 5 4 5 6 7
6 5 4 3 4 5 6
5 4 3 2 3 4 5
4 3 2 1 2 3 4
5 4 3 2 3 4 5
6 5 4 3 4 5 6
7 6 5 4 5 6 7
8 7 6 5 6 7 8
1 - 从给定坐标 (X;Y) 的起点
【问题讨论】:
尝试类似:
for(var i = 0;i<array.GetLength(0);i++)
{
for(var j = 0;j<array.GetLength(1);j++)
{
array[i,j] = 1 + Math.Abs(targetI - i) + Math.Abs(targetJ - j);
}
}
我认为这并不完美,但应该足以为您指明正确的方向。
【讨论】:
不需要递归:)
基本上,您希望用单元格坐标和目标坐标之间的Manhattan distance + 1 填充数组——即abs(x - tx) + abs(y - ty) + 1。
这里有一个 JavaScript 解决方案,它只打印出这样一个数组;留给读者作为练习(我一直想这么说!)将其翻译成 C# 并分配给您喜欢的数组。
function fillArray(w, h, targetX, targetY) {
for(var y = 0; y < h; y++) {
var t = [];
for(var x = 0; x < w; x++) {
t.push(Math.abs(x - targetX) + Math.abs(y - targetY) + 1);
}
console.log(t);
}
}
fillArray(7, 9, 3, 4);
示例输出:
[ 8, 7, 6, 5, 6, 7, 8 ]
[ 7, 6, 5, 4, 5, 6, 7 ]
[ 6, 5, 4, 3, 4, 5, 6 ]
[ 5, 4, 3, 2, 3, 4, 5 ]
[ 4, 3, 2, 1, 2, 3, 4 ]
[ 5, 4, 3, 2, 3, 4, 5 ]
[ 6, 5, 4, 3, 4, 5, 6 ]
[ 7, 6, 5, 4, 5, 6, 7 ]
[ 8, 7, 6, 5, 6, 7, 8 ]
【讨论】:
在你的代码中使用 Rec(x,y,0),其中 mas 是你的数组,maxx 和 maxy 是数组的大小
static public void Rec(int x, int y, int counter)
{
if (mas[x, y] == 0)
{
counter++;
mas[x, y] = counter;
if (x - 1 >= 0)
{
Rec(x - 1, y, counter);
if (y - 1 >= 0)
Rec(x - 1, y - 1, counter);
}
if (y - 1 >= 0)
{
Rec(x, y - 1, counter);
if (x + 1 <= maxx)
{
Rec(x + 1, y - 1, counter);
}
}
if (x + 1 <= maxx)
{
Rec(x + 1, y, counter);
if (y + 1 <= maxy)
{
Rec(x + 1, y + 1, counter);
}
}
if (y + 1 <= maxy)
{
Rec(x, y + 1, counter);
if (x - 1 >= 0)
{
Rec(x - 1, y + 1, counter);
}
}
}
}
【讨论】: