查找有向图中两个顶点之间是否存在路径
生活随笔
收集整理的這篇文章主要介紹了
查找有向图中两个顶点之间是否存在路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
查找有向圖中兩個頂點之間是否存在路徑
給定一個有向圖和其中的兩個頂點,檢查是否存在從第一個給定頂點到第二個頂點的路徑。
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 6Approach:
可以使用廣度優先搜索BFS或深度優先搜索DFS來查找兩個頂點之間的路徑。在BFS或DFS中取第一個頂點作為源點,然后開始執行。如果在我們的遍歷中找到第二個頂點,則返回 true 否則返回 false。
Alogrithm:
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
總結
以上是生活随笔為你收集整理的查找有向图中两个顶点之间是否存在路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新华三 VDI java,鱼和熊掌兼得:
- 下一篇: 导入导出redis数据和合并数据方法