如何从一个点填充二维数组中的数字越来越多

时间:2017-03-02 15:31:29

标签: c# arrays recursion

我想要实现的目标是:

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)的起始点

3 个答案:

答案 0 :(得分:3)

尝试类似:

SELECT `disctrict_field`, COUNT(*) FROM `table` GROUP BY `disctrict_field`

我不相信这是完美的,但它足以指出你正确的方向。

答案 1 :(得分:3)

不需要递归:)

基本上,您希望数组在单元格坐标和目标坐标之间填充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 ]

答案 2 :(得分:1)

在你的代码中使用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);
                }
            }
        }
    }
相关问题