繁体   English   中英

C#递归堆栈溢出崩溃

[英]c# Recursion stackoverflowcrash

我正在用C#开发一个扫雷游戏,而我的功能之一一直使程序崩溃。 erorr消息是Process is terminated due to StackOverflowException. 我试图在递归中找到问题所在,但没有找到问题。 仅在Openk才会发生此问题,因此我很确定问题在那里。 我试图找到是否存在无限递归,但没有找到。 可能是什么问题呢?

  public void Openk(int row, int col)
    {
        if (sqrs[row, col].IsBlank() == true)
        {
            for (int i = -1; i < 2; i++)
            {
                for (int j = -1; j < 2; j++)
                {                         
                    if (IsValid(row - i, col - j))
                    {                           
                            if (sqrs[row - i, col - j].IsMine() == false)
                                sqrs[row - i, col - j].Open();
                            Openk(row - i, col - j);

                    }                      
                }
            }
        }

    }
    public bool IsValid(int row, int col)
    {
        if (row >= n || row <= 0 || col >= n || col <= 0)
            return false;
        return true;
    }

您的问题是您Openk在同一中间广场上循环并执行Openk 也许是因为没有保护的if语句。 在您的代码中就像这样。

  1. 您传递选定的正方形坐标,例如[5,5]。
  2. 然后,您在5(4)之前的一行中循环,在5(6)之后的一行中循环。
  3. 对于每一行,在所选的第5列(4),第5列和下一个5列(6)之前循环一个正方形。
  4. 在您的代码中,仅当到达中间的正方形(i = 0,j = 0)时,才执行正方形的检查(如果它是我的),如果不是我的,则在减去零后传递所选坐标( i = 0,j = 0),有效地再次循环了同一点!

public void Openk(int row, int col)
{
    if (sqrs[row, col].IsBlank() == true)
    {
        for (int i = -1; i < 2; i++)
        {
            for (int j = -1; j < 2; j++)
            {
                // Only execute the following code when checking the middle square, where i = 0, and j = 0.
                if (i == 0 && j == 0) // Notice the braces I added, the code has the same effect if you don't type them.
                {   
                    // This if statement has not effect.
                    if (IsValid(row - i, col - j)) // It is like if (true)
                    {
                        if (sqrs[row-i, col-j].IsMine() == false)
                            sqrs[row - i, col - j].Open();
                        Openk(row - i, col - j); // row - 0 = row, col - 0 = col, your looping infinitely here.
                    }
                }
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM