[英]C++ “Maze” Assignment
迷你程序應該打印出迷宮中所有可能的路線,其中入口/起點總是從左上角向下一個,所有可能的出口總是在右牆上。 它從文本文件中檢索迷宮。
迷宮實際上只是一堆文字。 迷宮由一個nxn網格組成,由作為牆壁的“#”符號和表示可步行區域/路徑的各種字母[a ... z]組成。 信件可以重復,但永遠不能並排。
迷宮是15x15。
大寫字母S始終標記入口,位於第二高點的左側牆壁上。 可能的路徑只能通過字母 - 你不能走#符號。 右牆上的任何字母代表出口。
例如,
######
Sa#hln
#bdp##
##e#ko
#gfij#
######
是一個可能的迷宮。 我的小程序應該在讀取實際包含迷宮的文本文件后打印出所有可能的路徑。
對程序的調用將生成以下輸出到屏幕:
Path 1: S,a,b,d,e,f,i,j,k,o
Path 2: S,a,b,d,p,h,l,n
2 total paths
我該怎么做呢? 我不需要完整的代碼答案,我只想獲得一些如何解決這個問題的指導。
到目前為止,我已經完成了除了實際算法本身之外的所有事情,它們以遞歸方式檢查adajcent方塊以查看是否可以在它們上行走,而且我不知道我是如何在多條路徑上工作的。
這是我到目前為止(我知道我的路徑檢查錯了,但我不知道還能做什么):
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <cstdio>
using namespace std;
ifstream file("maze.txt");
vector<char> vec(istreambuf_iterator<char>(file), (istreambuf_iterator<char>())); // Imports characters from file
vector<char> path; // Declares path as the vector storing the characters from the file
int x = 18; // Declaring x as 18 so I can use it with recursion below
char entrance = vec.at(16); // 'S', the entrance to the maze
char firstsquare = vec.at(17); // For the first walkable square next to the entrance
vector<char> visited; // Squares that we've walked over already
int main()
{
if (file) {
path.push_back(entrance); // Store 'S', the entrance character, into vector 'path'
path.push_back(firstsquare); // Store the character of the square to the right of the entrance
// into vector 'path'.
while (isalpha(vec.at(x)))
{
path.push_back(vec.at(x));
x++;
}
cout << "Path is: "; // Printing to screen the first part of our statement
// This loop to print to the screen all the contents of the vector 'path'.
for(vector<char>::const_iterator i = path.begin(); i != path.end(); ++i) //
{
std::cout << *i << ' ';
}
cout << endl;
system ("pause"); // Keeps the black box that pops up, open, so we can see results.
return 0;
}
}
謝謝!
你需要做一些事情:
考慮從一個小得多的迷宮開始 - 也許是一個尺寸為3x3的迷宮 - 一條直線穿過地圖的路徑。 你的程序應該能夠解決這個問題。 然后將路徑更改為曲線。 然后使地圖更大。 讓路徑更難。 讓一些“紅鯡魚”分支出路。
較小的地圖,復雜性越來越高,應該使調試工作變得更加容易。 (如果您不知道如何使用調試器,那么啟動一個小問題將使學習調試器變得更容易。)
祝好運!
通常的方式(特別是對於學校作業)是遞歸地處理它。 從指定的起點開始。 從那里遞歸嘗試每個可能的方塊(上方,右側,下方)。
這里唯一真正的“技巧”是跟蹤你已經訪問過哪個方塊。 一種可能性是在輸入時將值保存在正方形中,然后在遞歸搜索其他正方形之前,將其設置為未使用的值(例如,“。”應該適用於您的情況)。
我首先要做的是在文件中讀取並將其放入數據結構中,以便您可以實際使用它。 如果這是作業,那么作業最有可能讓你學習路徑尋找算法,嘗試查找Dijkstra的算法,這應該讓你開始。
一種非常高級的方法:
創建一個樹,描述您可以通過迷宮的路徑。 打印出右側的那些。
你怎么會發現一條環繞自己的路徑? (或者你的迷宮不會有這個問題嗎?)
將符號加載到數組中。 然后遞歸檢查每個位置:它可以向上,向下,向左,向右嗎? 從那里,您可以將這些布爾答案保存為0或1在一個單獨的數組中,並使用它繼續...根據您的副本數組是否表示您可以或不能繼續在某個方向。
另外,肯定會制作一些新的方法...我通常會嘗試在主要方法中包含很少...
希望有所幫助,希望我有時間更多地看待它......
-P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.