版权声明:若想转载,请在显眼的地方附上文章来源。 https://blog.csdn.net/Abudula__/article/details/91459688
图的实现
图的实现有两种方法,一种是邻接矩阵,另一种是邻接表,这两种实现各有各的优缺点,以下给出了邻接表的实现并且DFS遍历的代码实现。
举例
// A simple representation of graph using STL #include<iostream> #include<vector> #include<list> using namespace std; // A utility function to add an edge in an // undirected graph. void addEdge(vector<list<int> >& adj,int i, int j) { adj[i].push_back(j); adj[j].push_back(i); } // A utility function to print the adjacency list // representation of graph void printGraph(vector<list<int> >& adj, int V) { for (int i = 0; i < V; ++i) { cout << "Adjacency list of vertex " << i << endl; for (auto j = adj[i].begin(); j != adj[i].end(); j++) cout << *j << " "; cout << endl; } } void DFS(vector<list<int> > &adj,int i,bool visited[]) { visited[i] = true; cout << i << " "; for (auto j = adj[i].begin(); j != adj[i].end(); j++) { if (!visited[*j]) DFS(adj, *j, visited); } } void DFStraverse(vector<list<int> > &adj) { bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) { if (!visited[i]) DFS(adj,i,visited); } } // Driver code int main() { int V = 4; vector<list<int> > adj(4); addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 2, 3); printGraph(adj,V); DFStraverse(adj); return 0; }
文章来源: https://blog.csdn.net/Abudula__/article/details/91459688