这是我第一次用C++编程,被要求编写一个广度优先搜索算法,给定以下类:
class route {
friend ostream& operator<<(ostream& os, const route& p);
public:
route(const string& startPlayer);
int getLength() const { return links.size(); };
void addConnect(const sport& s, const string& player);
void removeConnect();
const string& getLastPlayer() const;
private:
struct Connect {
sport s;
string player;
Connect() {}
Connect(const sport& s, const string& player) : s(s), player(player) {}
};
string startPlayer;
vector<Connect> links;
};
sport
是一个结构体,包含string name
和int players
。请问如何制作BFS?
谢谢!
编辑:
我了解BFS的算法,但由于我只编程过C语言,理解面向对象编程对我来说相当困难。在这个接口中,从哪里开始制作BFS呢?我是否需要创建一个新函数,将start string
与target string
进行比较?
namespace {
string promptForSPlayer(const string& prompt, const spdb& db)
{
string response;
while (true) {
cout << prompt << " [or <enter> to quit]: ";
getline(cin, response);
if (response == "") return "";
vector<sport> splist;
if (db.getsplist(response, splist)) return response;
cout << "It's not here: \"" << response << "\" in the sports database. "
<< "Please try again." << endl;
}
}
}
int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "Usage: sports" << endl;
return 1;
}
spdb db(argv[1]);
if (!db.good()) {
cout << "Failed to properly initialize the spdb database." << endl;
cout << "Please check to make sure the start files exist and that you have permission to read them." << endl;
exit(1);
}
while (true) {
string start = promptForSplayer("Player", db);
if (start == "") break;
string target = promptForSplayer("Another Player", db);
if (target == "") break;
if (start == target) {
cout << "Good one. This is only interesting if you specify two different people." << endl;
} else {
// replace the following line by a call to your generateShortestPath routine...
cout << endl << "No path between those two people could be found." << endl << endl;
}
}
return 0;
}