如何获得这个锯齿状阵列的最后位置?

Bra*_*ble 2 c#

我有一个这样的类,我使用作为数组中的点:

class Point
    {
        public int x;
        public int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后我试图获得最接近结束的值:

public void Position()
        {
            for (int x = 0; x < arr.Length; x++)
            {
                for (int y = 0; y < arr[x].Length; y++)
                {
                    if (arr[x][y] == 3)
                        Pos.x = x;
                        Pos.y = y;
                    if (arr[x][y] == 1)
                        Pos.x = x;
                        Pos.y = y;
                    if (arr[x][y] == 2)
                        Pos.x = x;
                        Pos.y = y;
                }
            }
            Console.Write("Last Position: {0}, {1}",LastPos.x, LastPos.y);
        }
Run Code Online (Sandbox Code Playgroud)

我有这个要点:

public Point Pos = new Point(0, 0);
Run Code Online (Sandbox Code Playgroud)

它是一个锯齿状的阵列,除了几个点外都是零.看起来像这样:

0 0 0 3 0 0 0 0

0 0 1 0 0 0 0

0 0 0 2 0 0 0 0

0 0 0 0 0

0 0 0 0 0 0 0

在这个例子中,2最接近末尾.位置为2,3,我想要Pos.x和Pos.y.它一直给我0,30.

Mar*_*ers 8

看起来你错过了一些花括号.

if (arr[x][y] == 3)
{
    Pos.x = x;
    Pos.y = y;
}
if (arr[x][y] == 1)
{
    Pos.x = x;
    Pos.y = y;
}
if (arr[x][y] == 2)
{
    Pos.x = x;
    Pos.y = y;
}
Run Code Online (Sandbox Code Playgroud)

在C#中,缩进并不重要,因此您的代码被解释为:

if (arr[x][y] == 3)
{
    Pos.x = x;
}
Pos.y = y;
if (arr[x][y] == 1)
{
    Pos.x = x;
}
Pos.y = y;
if (arr[x][y] == 2)
{
    Pos.x = x;
}
Pos.y = y;
Run Code Online (Sandbox Code Playgroud)

您还可以大大简化代码:

if (arr[x][y] != 0)
{
    Pos.x = x;
    Pos.y = y;
}
Run Code Online (Sandbox Code Playgroud)

另一个问题是你正在设置Pos但是打印的值LastPos.

如果你需要更好的性能,请注意,从结束开始向后搜索会更快,当你点击第一个非零元素而不是从开始搜索并记住你看到的最后一个非零元素时会更快.在许多情况下只检查几个元素后,这可能会终止 - 在最好的情况下,只需要检查一个元素.因此,根据数据的大小,这样做可能要快几百倍.