0

我正在尝试为 Windows Phone 创建自己的 WordSearch 游戏,并且找到了解决它的算法。我的问题是该算法使用递归,并且在 6-8 次调用后我得到了 StackOverflowException。

  • array : char[,] 包含二维表的字符
  • i,a:数组中当前位置的坐标
  • 宽度,高度:数组的大小
  • build:我们正在尝试创建的字符串(单词本身)
  • 覆盖: bool[,] 用于已使用的字符

这是算法:

...
enum WordType : byte
    {
        FullWord,
        PartialWord,
        FullWordAndPartialWord
    }  
...
static Dictionary<string, WordType> _words = new Dictionary<string, WordType>();
static Dictionary<string, bool> _found = new Dictionary<string, bool>();

void Search(char[,] array, int i, int a, int width, int height, string build, bool[,] covered)
        {            
            if (i >= width || i < 0 || a >= height || a < 0)
            {
                return;
            }            
            if (covered[a, i])
            {
                return;
            }

            char letter = array[a, i];

            string pass = build + letter;            
            WordType value;
            if (_words.TryGetValue(pass, out value))
            {                
                if (value == WordType.FullWord ||
                value == WordType.FullWordAndPartialWord)
                {                    
                    if (!_found.ContainsKey(pass))
                    {                        
                        _found.Add(pass, true);
                    }
                }

                if (value == WordType.PartialWord ||
                value == WordType.FullWordAndPartialWord)
                {

                    bool[,] cov = new bool[height, width];
                    for (int i2 = 0; i2 < width; i2++)
                    {
                        for (int a2 = 0; a2 < height; a2++)
                        {
                            cov[a2, i2] = covered[a2, i2];
                        }
                    }

                    cov[a, i] = true;

                    Search(array, i + 1, a, width, height, pass, cov);
                    Search(array, i, a + 1, width, height, pass, cov);
                    Search(array, i + 1, a + 1, width, height, pass, cov);
                    Search(array, i - 1, a, width, height, pass, cov);
                    Search(array, i, a - 1, width, height, pass, cov);
                    Search(array, i - 1, a - 1, width, height, pass, cov);
                    Search(array, i - 1, a + 1, width, height, pass, cov);
                    Search(array, i + 1, a - 1, width, height, pass, cov);
                }
            }
        }

当我调用它时:

 for (int i = 0; i < width; i++)
            {
                for (int a = 0; a < height; a++)
                {
                    Search(array, i, a, width, height, "", covered);
                }
            }

我能做些什么来避免异常?

4

0 回答 0