【发布时间】:2015-03-05 14:16:17
【问题描述】:
我最近开始了 C++ 编程,我想知道如何实现深度优先或广度算法。我一直在尝试这样做,但是我失败了,所以如果您可以使用提供的示例向我展示,那将非常有帮助。
#include <iostream>
#include <cstdlib>
using namespace std;
struct AdjancancyListNode
{
int destination;
struct AdjancancyListNode* next;
};
struct AdjancancyList
{
struct AdjancancyListNode *head;
};
class Graph
{
private:
int V;
struct AdjancancyList* array;
void DFSUtil(int v, bool visited[]);
public:
Graph(int V)
{
this->V = V;
array = new AdjancancyList [V];
for (int i = 0; i < V; ++i)
array[i].head = 0;
}
/*
* Adding Edge to Graph
*/
void addEdge(int s, int destination)
{
AdjancancyListNode* newNode = newAdjListNode(destination);
newNode->next = array[s].head;
array[s].head = newNode;
newNode = newAdjListNode(s);
newNode->next = array[destination].head;
array[destination].head = newNode;
}
/*
* Creating New Adjacency List Node
*/
AdjancancyListNode* newAdjListNode(int destination)
{
AdjancancyListNode* newNode = new AdjancancyListNode;
newNode->destination = destination;
newNode->next = 0;
return newNode;
}
/*
* Print the graph
*/
void printGraph()
{
int v;
for (v = 0; v < V; ++v) /* going through the edges */
{
AdjancancyListNode* pCrawl = array[v].head;
cout<<endl<<" Adjacency list of vertex |"<<v<<"|"<<endl<<" head ";
while (pCrawl)
{
cout<<"-> |"<<pCrawl->destination<<"|";
pCrawl = pCrawl->next;
}
cout<<endl;
}
}
};
int main()
{
Graph gh(9); /* declaring the graph with 5 vertexes */
gh.addEdge(0, 1);/* Adding edges */
gh.addEdge(0, 3);
gh.addEdge(1, 2);
gh.addEdge(1, 3);
gh.addEdge(2, 4);
gh.addEdge(2, 3);
gh.addEdge(4, 5);
gh.addEdge(5, 6);
gh.addEdge(5, 1);
gh.addEdge(3, 9);
gh.addEdge(8, 7);
gh.addEdge(7, 0);
gh.addEdge(9, 1);
// print the adjacency list representation of the above graph
gh.printGraph(); /* showing the graph*/
return 0;
}
【问题讨论】:
-
正确定义你的问题,否则这个问题肯定会被关闭,写下你尝试了什么以及你遇到了什么问题
-
你能不能再客气一点我才刚刚开始,我只是需要帮助,所以如果你想帮助,如果你不这样做,请不要讨厌,留给自己: ) 谢谢你
标签: c++ c algorithm depth-first-search breadth-first-search