0

I have got a set of nodes and few edges that represent which nodes are connected. V_nodes 1 7 22 97 48 11 V_arcs (1 22) (97 22) (7 1) (11 48) (48 7) (11 0) V_weight 1

I have created its adjacency matrix that shows 1 for connected and 0 for disconnected vertices. Now I want to implement a Depth First Traversal for this graph using its Adjacency Matrix. I have seen the tutorials on DFS but I am confused How can I traverse it using my Adjacency matrix. I just need to print the nodes using Depth First Traversal. Any help will be appreciated.

// Prints the adjacency matrix

cout<<"Adjacency Matrix : \n";
for(int i=0;i<6;i++)
    cout<<"       "<<nodes[i].nodevalue;
cout<<endl<<endl;

for(int i=0;i<6;i++)
{
    for (int j=0;j<6;j++)
    {
        cout<<"       "<<edges[i][j];
    }
    cout<<endl<<nodes[i].nodevalue;
    cout<<endl<<endl;
}
Faizan
  • 1,847
  • 8
  • 40
  • 63

2 Answers2

1

You'll want to use a last-in first-out queue, otherwise known as a stack. You could also use recursion, but you risk having a stack overflow if you graph is too large.

For each node, loop through all the nodes that node is connected to, adding them to the stack.

Pop the first node off of the stack, do whatever operation you wanted to do, and then repeat the process.

This could look like

void dfs(int node){
  std::stack<int> expand;
  expand.push(node);
  while(!expand.empty()){
    int tnode=expand.top();expand.pop();
    do_operation_on(tnode);
    for(int i=0;i<ADJACENCY_MATRIX_DIMENSION;i++)
      if(adj_matrix[tnode][i])
        expand.push(i);
  }
}

Note that if you have a cycle in your graph there will be problems.

Richard
  • 56,349
  • 34
  • 180
  • 251
  • I have tried exactly your code, but it does not print the depth first traversal. In my main(), I have called it with any random starting node, inside dfs I am trying to print tnode. What am I doing wrong ? What do you mean by a cycle in graph I don't think there is any loop in my graph. such that it starts and ends on the same node. is that a cycle? – Faizan Dec 30 '12 at 13:07
  • You cannot have tried exactly my code because the `do_operation_on` function was not defined. I'm afraid I don't understand what you mean by "it does not print e". Please explain. – Richard Dec 30 '12 at 13:09
  • ~void dfs(int node) { std::stack expand; expand.push(node); while(!expand.empty()){ int tnode=expand.top(); expand.pop(); cout< – Faizan Dec 30 '12 at 13:10
  • I am sorry , I am new here I don't know how add inline code in comments.Anyway the program prints the nodes but in a random way not as expected bfs. Is there any online tool available that allows to insert nodes & connects them & then displays the bfs of user's graph. Like a java applet or so ? – Faizan Dec 30 '12 at 13:16
  • 1
    To clarify - FIFO is for queue and LIFO is for stack - "Stack, abstract data type and data structure based on the principle of Last In First Out (LIFO)"(http://en.wikipedia.org/wiki/Stack_(abstract_data_type)) – SChepurin Dec 30 '12 at 13:20
  • @Faizan, the nodes are displayed non-randomly. Your question asked about _depth_-first search. If you want a _breadth_-first search replace the stack with a first-in, first-out [queue](http://www.cplusplus.com/reference/queue/queue/). – Richard Dec 30 '12 at 13:21
  • Thanks, @SChepurin, I'd just noticed that I messed that up myself. – Richard Dec 30 '12 at 13:22
  • Also, @Faizan, depending on how your matrix is set up you may need to replace `adj_matrix[tnode][i]` with `adj_matrix[i][tnode]`. – Richard Dec 30 '12 at 13:27
  • Actually I have to implement both traversals. I thought Depth First would be easy to implement that why I asked about DFS in the question. Even tough you have provided the code for DFS, but its is not printing in DFS way. Please help me out with this thing, I have been doing this whole day. What changes do I need to do ? I have a 2D array {adjacency matrix] , I just want to print the nodes in BFS traversal. thats it ! – Faizan Dec 30 '12 at 13:28
  • Can I pass any starting node while calling this function like : `dfs(1);` Basically my nodes are stored in 1D array. I am passing 1 as a test node just to check whether it traverses correct or not. Calling the function like this gives output : `1 4 5` . whereas my nodes are `1 7 22 97 48 11 ` as stated in the question. – Faizan Dec 30 '12 at 13:37
  • I am asking about Depth First Traversal ! Sorry I wrote BFS in above comment. – Faizan Dec 30 '12 at 13:39
  • 1
    @Faizan, perhaps your nodes have some kind of name? In that case you would want to replace `cout< – Richard Dec 30 '12 at 13:40
  • Thanks, atleast the nodes are printing now. But whatever I do it only print outs 3 nodes not all of them. My nodes are stored in `nodearray[6]` and iam passing `tnode` as index for nodearray. I have made the following changes & it prints `7 1 22`. `cout< – Faizan Dec 30 '12 at 13:53
  • @Faizan, if your adjaceny graph is indeed `(1 22) (97 22) (7 1) (11 48) (48 7) (11 0)` then the algorithm is working correctly. There is nowhere you can go from 22 so it terminates. It seems that you can not print every node by starting from a single given node. Do you want to print _every_ node? If so, you should seed the algorithm by pushing multiple nodes into the stack/queue at the beginning and keeping track of which nodes you have visited. Does that make sense? One does not typically use DFS/BFS to print an entire graph. – Richard Dec 30 '12 at 14:11
0
    #include<cstdio>
    #include<iostream>
    #include<stack>
    #include<cstring>
    using namespace std;
    int G[10][10],n;
    void dfs(int strt)
    {
        int vis[n];
        memset(vis,0,sizeof vis);
        stack<int>st;
        st.push(strt);
        while(!st.empty())
        {
            int pre=st.top();st.pop();

            if(!vis[pre])
            {
                cout<<pre<<" ";
                vis[pre]=1;
                for(int i=n-1;i>=0;i--)
                {

                    if(G[pre][i]==1 and !vis[i])
                    {
                        st.push(i);
                    }
                }
            }
        }
        cout<<endl;
    }
    int main()
    {
        cin>>n;
        for(int i=0;i<n;i++)
           for(int j=0;j<n;j++)
            cin>>G[i][j];
        dfs(2);
    }

Here i am adding the nodes that are connected to node in reverse order,its working. https://ideone.com/AGm2xe

benka
  • 4,732
  • 35
  • 47
  • 58