[英]Ways optimize my recursive maze solver?
我開發了以下C程序,以找到迷宮中所有可能的路徑。 它必須穿過迷宮中的每個房間。 這就是為什么'54'在這一刻要進行硬編碼的原因,因為我經過的8 * 7陣列有54個開放房間。 我將解決這個問題並在重新編寫時動態傳遞它。 但是,我正在尋求有關如何使代碼更高效的幫助-它找到了300,000條可能的路徑來完成我傳遞的迷宮,但運行了將近一個小時。
#include <stdio.h>
#define FALSE 0
#define TRUE 1
#define NROWS 8
#define MCOLS 7
// Symbols:
// 0 = open
// 1 = blocked
// 2 = start
// 3 = goal
// '+' = path
char maze[NROWS][MCOLS] = {
"2000000",
"0000000",
"0000000",
"0000000",
"0000000",
"0000000",
"0000000",
"3000011"
};
int find_path(int x, int y, int c, int *t);
int main(void)
{
int t = 0;
if ( find_path(0, 0, 0, &t) == TRUE )
printf("Success!\n");
else
printf("Failed\n");
return 0;
}
int find_path(int x, int y, int c, int *t)
{
if ( x < 0 || x > MCOLS - 1 || y < 0 || y > NROWS - 1 ) return FALSE;
c++;
char oldMaze = maze[y][x];
if ( maze[y][x] == '3' && c == 54)
{
*t = *t+1;
printf("Possible Paths are %i\n", *t);
return FALSE;
}
if ( maze[y][x] != '0' && maze[y][x] != '2' ) return FALSE;
maze[y][x] = '+';
if ( find_path(x, y - 1, c, t) == TRUE ) return TRUE;
if ( find_path(x + 1, y, c, t) == TRUE ) return TRUE;
if ( find_path(x - 1, y, c, t) == TRUE ) return TRUE;
if ( find_path(x, y + 1, c, t) == TRUE ) return TRUE;
maze[y][x] = oldMaze;
return FALSE;
}
首先,我看不到該函數返回TRUE的任何基本條件,它僅在遞歸調用自身時返回TRUE,巫婆表示它將始終打印失敗的結果(我認為遞歸必須具有一個基本條件,當找到成功將向上傳播。)
其次,您能否解釋一下方框中的值? 如0,1,2和3? 3是迷宮的盡頭還是?...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.