图的连通性

时间:2009-12-03 00:47:26

标签: graph depth-first-search

int dfs(int graph[MAXNODES][MAXNODES],int visited[],int start) {
int stack[MAXNODES];
    int top=-1,i;
    visited[start]=1;
    stack[++top]=start;
    while(top!=-1)
    {
  start=stack[top];
        for(i=0;i<MAXNODES;i++) {
   if(graph[start][i]&&visited[i]==0) {
                stack[++top]=i;
                printf("%d-",i);
                visited[i]=1;
                break;
            }
        }
  if(i==MAXNODES)
            top--;
    }
    return 0;
}

上面的代码在存储为Adjacency Matrix的Graph上实现dfs,我请求一个建议,我应该做些什么改变来知道生成的图是否连接。

3 个答案:

答案 0 :(得分:2)

请参阅我之前关于强关联组件的answer问题。

您的dfs写入效率也非常低,因为您重复开始i = 0扫描;你的堆栈应该记住你离开的地方并从那里继续。递归更自然,但如果你有一个有限的调用堆栈大小,那么显式堆栈是最好的(仅适用于大树)。

这是一个递归的dfs。如果你对存储dfs树不感兴趣,你只需在前驱[]中存储1,而不是从你到达它的节点中存储1:

const unsigned MAXNODES=100;

/* predecessor must be 0-initialized by the caller; nodes graph[n] that are
 reached from start will have predecessor[n]=p+1, where graph[pred] is the
 predecessor via which n was reached from graph[start].
 predecessor[start]=MAXNODES+1 (this is the root of the tree; there is NO
 predecessor, but instead of 0, I put a positive value to show that it's
 reached).

 graph[a][b] is true iff there is a directed arc from a->b

 */

void dfs(bool graph[MAXNODES][MAXNODES],unsigned predecessor[]
         ,unsigned start,unsigned pred=MAXNODES) 
{
    if (predecessor[start]) return;
    predecessor[start]=pred+1;
    for (unsigned i=0;i<MAXNODES;++i)
        if (graph[start][i])
            dfs(graph,predecessor,i,start);
}

这是上面描述的非递归dfs,但为predi使用相同的堆栈变量(通常,每个局部变量和参数都有一个堆栈变量改变你的递归):

void dfs_iter(bool graph[MAXNODES][MAXNODES],unsigned predecessor[]
              ,unsigned start)
{
    unsigned stack[MAXNODES]; // node indices
    unsigned n,pred;
    int top=0;
    stack[top]=start;
    for(;;) {
    recurse:
        // invariant: stack[top] is the next (maybe reached) node
        n=stack[top];
        if (!predecessor[n]) { // not started yet
            pred=top>0?stack[top-1]:MAXNODES;
            //show(n,pred);
            predecessor[n]=pred+1;
            // the first thing we can reach from n
            for (unsigned i=0;i<MAXNODES;++i)
                if (graph[n][i] && !predecessor[i]) {
                    stack[++top]=i; goto recurse; // push
                }
        }
        if (top>0) {
            pred=stack[top-1];
            // the next thing we can reach from pred after n
            for (unsigned i=n+1;i<MAXNODES;++i)
                if (graph[pred][i]) {
                    stack[top]=i; goto recurse; // replace top
                }
            --top;
        } else
            return;
    }
}

这可以在没有goto的情况下构建(它只是一个命名继续到最外面的循环),但在我看来没有更真实的清晰度。

无论如何,递归调用要简单得多。有Tarjan's strongly connected components algorithm的递归伪代码,你可以直接转录。如果你需要帮助使其非递归(显式堆栈),请询问。

答案 1 :(得分:1)

您需要存储从一个节点到下一个节点行进所生成的边缘。然后,您可以验证图中的所有节点是否通过边连接。

答案 2 :(得分:0)

运行Dijkstra的算法。如果最后您的队列为空并且某些顶点未着色,则表示图形未连接。这是保证线性时间,dfs方法具有二次方的最坏情况分析。