简体   繁体   中英

Depth first search(DFS) coding

#include<iostream>

void DFS(int);
int G[10][10], visited[10], n;

//G->Adjacency Matrix, n->no of vertices

void main()
{
int i,j;
cout<<"Enter vertices";
cin>>n
cout<<"Enter adjacency matrix";
for(i=0;i<n;i++)
    for(j=0;j<n;j++)
        cin>>G[j][i];

for(i=0;i<n;i++)
    visited[i]=0

DFS(0);

void DFS(int i)
{
int j;
cout<<"\n"<<i;
visited[i]=1;
for(j=0;j<n;j++)
    if(!visited[j] && G[i][j]==1)
            DFS(j);
}

What does the !visited[j] in the if condition mean? I understand that once you visit any node, you have to make the node bit in the array as 1, but how do we apply the not condition for any array?

Here visited[] working like a flag. I hope you understood how the algorithm works(If not try to understand it first). You know DFS always goes with depth.That is if it gets 3 as a leaf 2 then it will go node 3 and search for leaves of 3. So consider a graph where node 1 is connected with 2, 2 is connected with 3 and 3 is connected with 1. If we run a DFS from node 1 it will go as follows: 1->2->3->1->2->3 and so on which will never terminate. To avoid cycle like that we mark current node as visited and only visit those node which are not visited before.

With !visited[j] it means that j-th node is not visited before.

In depth-first search the idea is to travel as deep as possible from neighbor to neighbor before backtracking. What determines how deep is possible is that you must follow edges, and you don't visit any vertex twice (!visited[j])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM