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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

LeetCode 1971. Find if Path Exists in Graph(图的遍历)

發布時間:2024/7/5 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 1971. Find if Path Exists in Graph(图的遍历) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive).
The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi.
Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

You want to determine if there is a valid path that exists from vertex start to vertex end.

Given edges and the integers n, start, and end, return true if there is a valid path from start to end, or false otherwise.

Example 1:

Input: n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2 Output: true Explanation: There are two paths from vertex 0 to vertex 2: - 012 - 02

Example 2:

Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 5 Output: false Explanation: There is no path from vertex 0 to vertex 5.Constraints: 1 <= n <= 2 * 10^5 0 <= edges.length <= 2 * 10^5 edges[i].length == 2 1 <= ui, vi <= n - 1 ui != vi 1 <= start, end <= n - 1 There are no duplicate edges. There are no self edges.

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-if-path-exists-in-graph
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

  • 圖的遍歷,BFS、DFS都可以
class Solution:def validPath(self, n: int, edges: List[List[int]], start: int, end: int) -> bool:from queue import Queueg = [[] for _ in range(n)]for e in edges:g[e[0]].append(e[1])g[e[1]].append(e[0])vis = [0]*nq = Queue()q.put(start)vis[start] = 1while not q.empty():id = q.get()if id == end:return Truefor nid in g[id]:if vis[nid] == 0:vis[nid] = 1q.put(nid)return False

312 ms 66.1 MB Python3


我的CSDN博客地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!

總結

以上是生活随笔為你收集整理的LeetCode 1971. Find if Path Exists in Graph(图的遍历)的全部內容,希望文章能夠幫你解決所遇到的問題。

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