Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dfs algorithms uses queue?

i have seen in internet following DFS algorithm

#include<iostream>
#include<queue>
#define MAX 100

using namespace std;

queue<int> myQueue;
int G[MAX][MAX];
int visit[MAX];
int V, E;


void dfs(int s) {
     int i, j, node;
     memset(visit, 0, sizeof(visit));
     myQueue.push(s);

     while(!myQueue.empty())
     {
          node = myQueue.front();
          myQueue.pop();
          if(visit[node]) continue;
          visit[node] = 1;
          cout << node << " ";

          for(i=0; i<V; i++)
               if(G[i][node]) myQueue.push(i);
          for(j=0; j<V; j++)
               if(G[node][j]) myQueue.push(j);     
     }

}

int main() {
    memset(visit, 0, sizeof(visit));
    dfs(0);
    return 0;
}

my question is that it uses queue instead of stack, so is it correct?also when i should enter graph,should it be like adjacent matrix or?please help me,this algorithm uses default values,so how can i change it?


1 Answers

Interesting. I found the code you are referring to http://www.koders.com/cpp/fid1107E4F79ED191B482853E3206A2F13FC77B4310.aspx.

Sure enough that uses the queue class from the Standard C++ Library and, as such, implements a breadth-first search algorithm. Using a C++ stack should give you the depth-first search you desire.

Goes to show you can't trust everything you see on the Internet (perhaps even including this answer). :-)

As to your second question, this posted code is indeed using an adjacency matrix. In fact, you can even be more precise and say, by inspecting the code, that it is implementing a undirected graph without parallel edges.

ADDENDUM

The code in action, showing it is a BFS: http://ideone.com/mLl23

like image 73
Ray Toal Avatar answered Mar 24 '26 03:03

Ray Toal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!