存储最短路径DFS

时间:2017-04-08 10:09:30

标签: c graph depth-first-search path-finding

我创建了一个带有邻接列表的图形,并使用DFS算法找到最短路径。 但是我只能打印出程序在图表中的位置,但我不知道如何保存最短路径。 这里是代码

int path[1000];
int j = 0;


t_graph         *create_graph(int v)                                                                      
{                                                                                                         
  int           i = 0;                                                                                        
  t_graph       *graph;                                                                                   

  if ((graph = malloc(sizeof(*graph))) == NULL)                                                           
    return (NULL);                                                                                        
  graph->v = v;                                                                                           
  if ((graph->arr = malloc(sizeof(t_list) * v)) == NULL)                                                  
    return (NULL);                                                                                        
  while (i < v)                                                                                           
    {                                                                                                     
      graph->arr[i].visited = 0;                                                                          
      graph->arr[i++].head = NULL;                                                                        
    }                                                                                                     
  return (graph);                                                                                         
} 


int find_path(t_graph *graph, int nb, int end)
{
 t_node *node;
 int i;

 i = 0;
 graph->arr[nb].visited = 1;
 path[j++] = nb;
 while (node)
   {
    if (node->nb == end)
      {
        path[j++] = node->nb;
        while (i < j)
          {
            printf("%d -> ", path[i++]);
          }
        printf("\n");
        j--;
      }
    if (graph->arr[node->nb].visited == 0)
      find_path(graph, node->nb, end);
    node = node->next;
   }
   j--;
}

我通过添加2次j--来修改我的代码,就像我的数组中的回溯一样,它工作得更好,但我有一些错误。 例如我想从0到5,它会给我1-2-3-4-5但也会给1-2-3-4-5-6-5。 你对如何解决这个问题有任何想法吗?

所以我尝试将路径存储在一个数组中,如果邻居是结尾,我打印这个数组,但它不起作用。 我认为这是因为如果路径不好,我不会回到数组中,如果找到路径,我就不能很好地处理递归。

这里我如何调用该函数

find_path(graph, 0, 7);

我从节点n°0开始,想要转到节点n°7。

0 个答案:

没有答案