我正在尝试为Windows Phone创建自己的WordSearch游戏,我找到了解决它的算法。我的问题是该算法使用递归,我在6-8次调用后得到一个StackOverflowException。
以下是算法:
...
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);
}
}
我可以做些什么来避免异常?