我已经在这些概念中苦苦挣扎了近一个星期而且一直无处可去!我理解邻接列表图如何在纸上工作,并且可以为我想要做的所有事情扼杀基本算法......但我似乎无法以任何可用的形式编写代码!我的目标是使用邻接列表来获得一个未加权的有向图,该邻接列表从文件中读取字符串并将它们转换为节点。我想用一个向量来保存节点。
我最初的想法是有一些(坏的伪代码): *更新
Class of Graph
vector<string> list1
vector<string> list2
void addNode (string) //checks if node already exists in vector, if yes- do nothing, if no - add node to vector
//if <node> apears in <list1>
//do nothing
//else
//add <node> to list 1
list1.pushback (string)
void addEdge (node_1, node_2)//connects nodes to form edge
//point location of <string> in list1 to location in list2
void searchList //searches through list using DFS
void printGraph //prints graph using DFS
bool hasLink //checks to see if its linked
bool hasCycle //checks to see if
到目前为止,这是我唯一有效的实际代码
int main(int argc, char* argv[])
{
if (argc<2) {
cout << "Filename not given." << endl;
return 1;
}
ifstream infile;
infile.open(argv[1]);
int nodes = 0;
//int edges = 0;
istringstream Node_1;
istringstream Node_2;
char delimiter = ' ';
string line;
string token;
//want a loop that does all this while there's still an unread line
//current one won't terminate
while(infile){
getline(infile, line); //reads in each line
//check for spaces
token = line.substr(0,line.find(delimiter));
//node strings
string node_1 = token.substr(0,token.find('-'));
string node_2 = token.substr(token.find('-')+1,token.length());
//cout << node_1 << endl << node_2 <<endl;
nodes = nodes + 2;
//edges++;
//addNode(node_1);
//addNode(node_2);
//addEdge(node_1, node_2);
}
//printGraph
//hasCycle
//hasLink
//cout << "Read " << nodes << " cities and" << edges << " edges" << endl;
return 0;
}
示例输入:
Chicago,IL-Muncie,IN Chicago,IL-Fort_Wayne,IN
Cincinnati,OH-Fort_Wayne,IN Cincinnati,OH-Bloomington,IN