我正在尝试编写算法来解决随机攀爬的随机8拼图。 我用首选,最佳选择和随机重启来写它,但它们总是陷入无限循环。任何方法来防止这种情况? 当生成随机谜题时,我使用一种算法来确保所产生的所有谜题都是可解的。所以在可解决性方面没有问题。 这里是随机重启类型的功能,它可以解决近100%的谜题中的8个谜题:
public static bool HillClimbingRandomRestart(int[,] _state)
{
int[,] _current = _state;
int hMax = Problem.GetHeuristic(_state);
int Counter = 0;
int _h = hMax;
int[,] _best = _current;
int[,] _next = _current;
while (Counter < 100000)
{
Counter++;
if (isGoal(_current))
return true;
foreach (Move suit in Enum.GetValues(typeof(Move)))
{
_next = Problem.MoveEmptyTile(_current, suit);
if (_next == null)
continue;
_h = Problem.GetHeuristic(_next);
if (_h < hMax)
{
hMax = _h;
_best = _next;
}
}
if (_current == _best)
{
Random rnd = new Random();
int[,] _nextRandom = Problem.MoveEmptyTile(_current, (Move)rnd.Next(4));
while(_nextRandom==null)
_nextRandom = Problem.MoveEmptyTile(_current, (Move)rnd.Next(4));
_current = _nextRandom;
}
else
_current = _best;
hMax = Problem.GetHeuristic(_current);
}
return false;
}