我在迷宫中导航的递归算法花费的时间太长了。关于如何加快速度以提高效率的任何建议?现在,它通过了所有可能的解决方案。当我试图减少它时,它会跳过许多解决方案,包括最短的解决方案。如何减少解决方案的数量,或提前结束一些解决方案,同时不跳过最短的解决方案?
private static void turnsforshortestmove(Vector2 location, int[,] board, int endrow, ref Boolean done, ref int[,] BOARDCHANGE, ref HashSet<int> h)
//location is current location. board is the maze, endrow is the end y value to get to. it doesn't matter which x value, but as long as they get to the y value it's considered finishing.
// done is a mistake, ignore it. BOARDCHANGE stores
{
//i need to compare all results for shortest
//i need to cut off those that cant move
if (location.Y == endrow)
{
h.Add(parseInt(board)); //counts how long the path is
for (int r = 0; r < 19; r++)
for (int c = 0; c < 19; c++)
BOARDCHANGE[r, c] = board[r, c]; //sets the "real" board to have the path shown
}
else
{
int[,] boardCopy = new int[19, 19];
for (int r = 0; r < 19; r++)
for (int c = 0; c < 19; c++)
boardCopy[r, c] = board[r, c];
boardCopy[(int)location.X, (int)location.Y] = 8;
//this part is saying if the square above isnt a wall, and two squares above isn't occupied, then do this function again
if (boardCopy[(int)location.X, (int)location.Y - 1] == 1)
{
if (boardCopy[(int)location.X, (int)location.Y - 2] == 0)
{
turnsforshortestmove(new Vector2(location.X, location.Y - 2), boardCopy, endrow, ref done, ref BOARDCHANGE, ref h);
}
}
if (boardCopy[(int)location.X - 1, (int)location.Y] == 1)
{
if (boardCopy[(int)location.X - 2, (int)location.Y] == 0)
{
turnsforshortestmove(new Vector2(location.X - 2, location.Y), boardCopy, endrow, ref done, ref BOARDCHANGE, ref h);
}
}
if (boardCopy[(int)location.X + 1, (int)location.Y] == 1)
{
if (boardCopy[(int)location.X + 2, (int)location.Y] == 0)
{
turnsforshortestmove(new Vector2(location.X + 2, location.Y), boardCopy, endrow, ref done, ref BOARDCHANGE, ref h);
}
}
if (boardCopy[(int)location.X, (int)location.Y + 1] == 1)
{
if (boardCopy[(int)location.X, (int)location.Y + 2] == 0)
{
turnsforshortestmove(new Vector2(location.X, location.Y + 2), boardCopy, endrow, ref done, ref BOARDCHANGE, ref h);
}
}
}
}
最后,它通过 Hashset 查找最短路径(数字)。