日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

查找有向图中两个顶点之间是否存在路径

發布時間:2024/1/1 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 查找有向图中两个顶点之间是否存在路径 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

查找有向圖中兩個頂點之間是否存在路徑

給定一個有向圖和其中的兩個頂點,檢查是否存在從第一個給定頂點到第二個頂點的路徑。

Consider the following Graph:Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : (u, v) = (3, 0) Output: No Explanation: There is no path from 3 to 6

Approach:

可以使用廣度優先搜索BFS深度優先搜索DFS來查找兩個頂點之間的路徑。在BFS或DFS中取第一個頂點作為源點,然后開始執行。如果在我們的遍歷中找到第二個頂點,則返回 true 否則返回 false。

Alogrithm:

  • 下面的實現是使用 BFS
  • 創建一個隊列和一個最初填充為 0、大小為 V 的visited數組,其中 V 是頂點數
  • 在隊列中插入起始節點,即把u 推入隊列并將u 標記為已訪問
  • while循環該隊列,直到隊列不為空
  • 使隊列的前元素出列,迭代其所有相鄰元素。如果有相鄰元素是目標頂點,則返回 true。推入隊列中所有相鄰和未訪問的頂點并將它們標記為已訪問
  • 由于 BFS 中未到達目的地,因此返回 false
  • Code:

    static class Graph {int V;List<Integer>[] adj;public Graph(int V) {this.V = V;adj = new List[V];for (int i = 0; i < V; i++) {adj[i] = new LinkedList<>();}}void addEdge(int u, int v) {adj[u].add(v);}/*** @param s 起始頂點 source* @param d 結束頂點 destination* @return*/boolean isReachable(int s, int d) {boolean[] visited = new boolean[V];Queue<Integer> queue = new LinkedList<>();queue.offer(s);visited[s] = true;while (!queue.isEmpty()) {int u = queue.poll();for (int v : adj[u]) {if (v == d) return true;if (!visited[v]) {visited[v] = true;queue.offer(v);}}}return false;}public static void main(String args[]) {// Create a graph given in the above diagramGraph g = new Graph(4);g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 2);g.addEdge(2, 0);g.addEdge(2, 3);g.addEdge(3, 3);int u = 1;int v = 3;if (g.isReachable(u, v))System.out.println("There is a path from " + u + " to " + v);elseSystem.out.println("There is no path from " + u + " to " + v);u = 3;v = 1;if (g.isReachable(u, v))System.out.println("There is a path from " + u + " to " + v);elseSystem.out.println("There is no path from " + u + " to " + v);}/*** There is a path from 1 to 3* There is no path from 3 to 1*/ }

    Reference

    • Find if there is a path between two vertices in a directed graph

    總結

    以上是生活随笔為你收集整理的查找有向图中两个顶点之间是否存在路径的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。