为图创建邻接列表的最佳方法是使用“前向列表”(考虑您的 C++ 语言)。如需更多参考,请访问https://www.geeksforgeeks.org/forward-list-c-set-1-introduction-important-functions/
请阅读以下代码以了解“转发列表”的说明注意:- 在阅读代码之前,请正确理解 STL 库为“转发列表”提供的实用函数。
/* The code has been designed to give output only if ENTER key is pressed,
before that it'll keep
recieving inputs from the user. So provide all your inputs in one line
seperated by whitespaces. */
/* This is the implementation of DFS */
#include<iostream>
#include<forward_list>
using namespace std;
class graph{
private:
int noOfVertices;
forward_list<int> *adj;
void dfsUtil(int v, bool *visited);
public:
graph(int v);
void addEdge(int s, int d);
void dfs(int startVertex);
};
graph::graph(int v){
noOfVertices = v;
adj = new forward_list<int>[noOfVertices];
}
void graph::addEdge(int s, int d){
adj[s].push_front(d);
}
void graph::dfs(int startVertex){
bool *visited = new bool[noOfVertices];
for(int i = 0 ; i < noOfVertices ; i++){
visited[i] = false;
adj[i].reverse();
}
dfsUtil(startVertex, visited);
}
void graph::dfsUtil(int v, bool *visited){
forward_list<int>::iterator i;
visited[v] = true;
cout << v << " ";
for(i = adj[v].begin() ; i != adj[v].end() ; i++){
if(!visited[*i])
dfsUtil(*i, visited);
}
}
int main(){
int v, s, d;
cin >> v;
graph g(v);
while(cin.peek() != '\n')
{
cin >> s >> d;
g.addEdge(s, d);
}
g.dfs(2);
}