#include//輸入輸出流
#include//檔案標頭檔案
#include#include//時間的標頭檔案
#include//使用系統標頭檔案
#include//字串標頭檔案
#include//棧標頭檔案
#include//數學函式標頭檔案
#include//命名函式
#define time 12//規定的遊戲時間
#define maxsize 1000 //棧最多的元素個數
using namespace std;
int **map;//迷宮二維動態陣列
int m, n;//迷宮行與列數
int start_x, start_y, end_x, end_y, x, y;//老鼠的開始位置,最終位置等全域性變數
int g;
int h;//老鼠的原位置
ofstream out;//將輸入的陣列寫入檔案
bool victory = false;//bool變數開始為假,為真時結束
//求最短路徑和所有路徑
struct mazeroute stack[maxsize], path[maxsize]; //定義棧和存放最短路徑的陣列
int top = -1; //棧頂指標
int count = 1; //路徑數計數
int minlen = maxsize; //最短路徑長度
void mazeframe(int x1, int y1, int x2, int y2)
cout << endl;
cout << "按回車鍵繼續···\n";
cout << endl;
if (top + 1> p;
switch (p)
}}//向上的函式
void up()
}//向下的函式
void down()
}//向右的函式
void right()
}//向左的函式
void left()
}int countlinesh(char *filename)
else
return n;
}in.close();//關閉檔案
}int countlinesz(char *filename)
if (isdigit(i))
}return n;
in.close();
}int main()
out << '\n';
}out.close();
break;
case 'n':break;
default:break;
}int count = 0;//字元總數
int hang = 0;//陣列行數
char p[50];
ifstream in;
int i;
cout << "請輸入要開啟檔案的路徑:";
cin >> p;
count = countlinesz(p);
hang = countlinesh(p);
m = hang;
n = count / m;//n為列數
start_x = (m - 1) / 2;//老鼠的初始位置
start_y = (n - 1) / 2;
end_x = m - 2;//糧倉的位置
end_y = n - 2;
x = start_x;
y = start_y;
g = 0;
h = 0;
map = (int**)malloc(sizeof(int*)*m);
for (int l = 0; l> i;//將檔案中的數字寫入記憶體
map[n][m] = i;//將記憶體中的資料寫入到陣列中 }}
//接下來是初始化
for (int sx = 0; sx> ch;
while (ch == 'y')
cout << "是否要改變牆與路?y or n :";
cin >> ch;
}draw();
clock_t start, finish;//即使開始和結束
double totaltime;//程式執行的總時間
start = clock();//計時開始
while (!victory)
}finish = clock();//計時結束
totaltime = (double)(finish - start) / clocks_per_sec;
cout << "\n此程式執行的總時間是" << totaltime << "秒!" << endl;
if (totaltime
以上是程式的截圖,我們可以手動控制鍵盤的方向鍵來控制老鼠的移動
a 演算法迷宮 c 迷宮中的老鼠
之前我們已經討論了採用回溯 backtracking 方法來解決西洋棋中馬的遍歷問題。為了讓大家更加熟悉回溯方法,我們將在後面的課程中再分析幾個例子。今天先看乙個使用回溯方法解決老鼠走迷宮的問題。下圖是乙個迷宮,其中塗上灰色的方格,老鼠不能進入,請找出老鼠從起點到終點的線路。老鼠只能向兩個方向移動 ...
老鼠走迷宮
說明 老鼠走迷宮是遞迴求解的基本題型,我們在二維陣列中使用2表示迷宮牆壁,使用1來表示老鼠的行走路徑,試以程式求出由入口至出口的路徑。解法 老鼠的走法有上 左 下 右四個方向,在每前進一格之後就選乙個方向前進,無法前進時退回選擇下乙個可前進方向,如此在陣列中依序測試四個方向,直到走到出口為止,這是遞...
老鼠走迷宮
老鼠走迷官 一 說明 老鼠走迷宮是遞迴求解的基本題型,我們在二維陣列中使用2表示迷宮牆壁,使用1來表 示老鼠的行走路徑,求出由入口至出口的路徑。解法 老鼠的走法有上 左 下 右四個方向,在每前進一格之後就選乙個方向前進,無法前 進時退回選擇下乙個可前進方向,如此在陣列中依序測試四個方向,直到走到出口...