C++ DFS/BFS算法的简短版本

C++ DFS/BFS算法的简短版本,c++,optimization,depth-first-search,breadth-first-search,C++,Optimization,Depth First Search,Breadth First Search,经常遇到图形上的奥运会问题,我总是为实现DFS编写一段相当长的代码,调试它花费了很多时间。我写了这样的结构: class Graph { int V; list<int> *adj; public: Graph(int V); void addEdge(int v, int w); void DFS(int s, int f); }; Graph::Graph(int V) { this->

经常遇到图形上的奥运会问题,我总是为实现DFS编写一段相当长的代码,调试它花费了很多时间。我写了这样的结构:


class Graph { 
    int V;   
    list<int> *adj;    
public: 
    Graph(int V);  
    void addEdge(int v, int w);  
    void DFS(int s, int f);   

}; 

Graph::Graph(int V) { 
    this->V = V; 
    adj = new list<int>[V]; 
} 

void Graph::addEdge(int v, int w) { 
    adj[v].push_back(w);  
    adj[w].push_back(v);
}

void Graph::DFS(int s,int f) { 
    vector<bool> visited(V, false); 
    stack<int> stack; 
    stack.push(s); 

    while (!stack.empty()) {  
        s = stack.top(); 
        stack.pop(); 

        if (!visited[s]) {
            cout << s << " "; 
            visited[s] = true; 
        } 

        for (list<int>::iterator i = adj[s].begin(); i != adj[s].end(); ++i) 
            if (!visited[*i]) 
                stack.push(*i); 
    }
}

类图{
INTV;
列表*adj;
公众:
图形(INTV);
无效补遗(整数v,整数w);
无效DFS(整数s,整数f);
}; 
图::图(intv){
这个->V=V;
adj=新列表[V];
} 
void图::addEdge(intv,intw){
形容词[v]。推回(w);
形容词[w]。推回(v);
}
void图::DFS(ints,intf){
向量访问(V,假);
堆叠;
堆叠。推送;
而(!stack.empty()){
s=stack.top();
stack.pop();
如果(!已访问[s]){
cout
void addEl(int a,int b,向量g[]){
g[a]。推回(b);
g[b]。推回(a);
}
void DFS(int s,int f,int n,向量g[])){
向量vis(n,假);
堆栈stk;
stk.push(s);
而(!stk.empty()){
s=stk.top();
stk.pop();
如果(!vis[s]){

如果你使用OOP来建模你的问题,我认为这是一个非常好的尺寸。另一方面,如果你在
main()
函数中使用过程编程,它的尺寸会更小。这里有什么问题?使用Boost graph library。请发布可编译的代码,还有什么是可更改的?
void addEl(int a, int b,  vector<int> g[]) {
    g[a].push_back(b);
    g[b].push_back(a);
}

void DFS(int s, int f, int n,  vector<int> g[]) {
    vector<bool> vis(n,false);
    stack<int> stk;

    stk.push(s);

    while(!stk.empty()) {
        s = stk.top();
        stk.pop();
        if(!vis[s]) {
            cout << s << endl;
            vis[s] = true;
            if(s==f) return;
        }
        for(int i=0;i<g[s].size();i++) {
            if(!vis[g[s][i]]) stk.push(g[s][i]);
        }
    }
}