【问题标题】:Path Finding used BFS in java路径查找在 java 中使用 BFS
【发布时间】:2018-03-06 21:03:19
【问题描述】:

我有这个代码,广度优先搜索 这段代码表示图,搜索算法广度搜索,我想请你对它提出问题,它是

   void BFS(int s)
   {
       // Mark all the vertices as not visited(By default
       // set as false)
       boolean visited[] = new boolean[V];

       // Create a queue for BFS
       LinkedList<Integer> queue = new LinkedList<Integer>();

       // Mark the current node as visited and enqueue it
       visited[s]=true;
       queue.add(s);

       while (queue.size() != 0)
       {
           // Dequeue a vertex from queue and print it
           s = queue.poll();
           System.out.print(s+" ");

           // Get all adjacent vertices of the dequeued vertex s
           // If a adjacent has not been visited, then mark it
           // visited and enqueue it
           Iterator<Integer> i = adjacent_List[s].listIterator();
           while (i.hasNext())
           {
               int n = i.next();
               if (!visited[n])
               {
                   visited[n] = true;
                   queue.add(n);
               }
           }
       }
   }

如果你从点0开始寻找第三点,我想按照路径,我该如何修改代码以打印它通过的点! 所以你将曲目存储在 Stack 中并打印出来

【问题讨论】:

  • "如何修改代码以打印它通过的点?" - 它已经做到了:System.out.print(s+" ");。如需更详细的帮助,请发帖 minimal reproducible example 并附上测试数据。

标签: search graph-theory breadth-first-search


【解决方案1】:

定义一个父数组,当您访问循环中的每个节点 n 时,您将设置 par[n]=s

最后你应该创建一个 for 循环来获得从 3 到 0 的父链

for (int i=3 ; i!=0 ; i=par[i])
    cout << i << " ";

【讨论】:

  • 这可能适用于没有循环的情况,因此每个顶点都有一个父节点。
  • @c0der BFS 创建一棵树,因此每 2 个节点之间只有一个路径。因此,每个顶点只有一个父节点
  • BFS 在这种情况下是一种搜索算法,可以在任何树上使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多