简体   繁体   English

深度优先搜索(DFS)编码

[英]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? if条件中的!visited [j]是什么意思? 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? 我知道一旦访问任何节点,就必须将数组中的节点位设置为1,但是我们如何将not条件应用于任何数组?

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. 您知道DFS总是随着深度前进的。也就是说,如果DFS成为3的叶子2,那么它将到达节点3并搜索3的叶子。因此,请考虑一个图,其中节点1与2连接,2与3和3连接与1连接。如果我们从节点1运行DFS,它将执行以下操作:1-> 2-> 3-> 1-> 2-> 3,依此类推,它将永远不会终止。 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. 使用!visited [j]意味着之前没有访问过第j个节点。

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]) 决定可能有多深的原因是您必须遵循边缘, 并且您两次都没有访问任何顶点(!visited [j])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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