How to find path of exact length in graph

前端 未结 5 1960
日久生厌
日久生厌 2021-01-23 04:30

I would like to find path of fixed length (given while running the program) in undirected graph. I\'m using adjacency matrix of my graph.
I tried to use some algorithms like

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 04:44

    A single dfs ought to be sufficient:

    void dfs(int start, int hops)
    {
      if(hops == k && start == t)
        {
          path++;
          return;
        }
      else if(hops >= k)
        return;
      for(int w = 1; w <= n; w++)
        if(routes[start][w])
          dfs(w, hops + 1);
    }
    

    Here, k is the length of the path and routes[][] is the adjacency matrix of the graph. path is a global variable. This can account for cycles - it takes into account ALL paths of a given length. From main, call

    path = 0;
    dfs(source, k);
    cout<

    Note that the number of nodes is one more than the number of hops. Also note that if the length the path is huge, this function stacks up quickly. No pun intended.

提交回复
热议问题