0

Constantly confronted with olympiad problems on graphs, I always wrote a rather long code for implementing DFS, and it took a lot of time to debug it. I wrote constructs like this:


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); 
    }
}

It was long and inconvenient, especially when changing one language to another. It is especially difficult when writing from scratch. I need an optimal approach to implement DFS / BFS as briefly and elegantly as possible, preferably in the form of a neat method that takes input values in the form (beginning, end).

c0der
  • 18,467
  • 6
  • 33
  • 65
Mouvre
  • 274
  • 2
  • 10

1 Answers1

0
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]);
        }
    }
}

Probably this is what I wanted(but without OOP)

Mouvre
  • 274
  • 2
  • 10