
這道題目要求我們判斷是否存在從起點到終點的有效路徑。這可以轉化為求圖中兩個頂點是否連通的問題。我們可以使用廣度優先搜尋 (BFS)、深度優先搜尋 (DFS)或 Disjoint Set Union (DSU) 來解決這個問題。這些方法都可以幫助我們快速地找到兩個頂點之間是否存在一條有效路徑。
來,一起準備面試吧!
讓我們一起寫一份超級吸睛的履歷吧!從技術主管的視角,幫助你用精練語句量化成效,讓你的履歷表變得更加出色。別再猶豫了,動動手指投遞履歷吧!
立即加入 Line 讀書會,一起準備面試吧!
履歷諮詢
加入讀書會 (邀請碼:2573)
我們要用廣度優先搜尋 (BFS) 來判斷從起點到終點是否有有效的路徑。具體的步驟如下:
true。false。class Solution {
   fun validPath(n: Int, edges: Array<IntArray>, source: Int, destination: Int): Boolean {
        val graph = buildGraph(edges)
        return hasPathBFS(graph, source, destination)
    }
    private fun buildGraph(edges: Array<IntArray>): Map<Int, List<Int>> {
        val graph = mutableMapOf<Int, List<Int>>()
        edges.forEach { edge ->
            val a = edge[0]
            val b = edge[1]
            graph[a] = (graph[a] ?: emptyList()) + b
            graph[b] = (graph[b] ?: emptyList()) + a
        }
        return graph
    }
    private fun hasPathBFS(graph: Map<Int, List<Int>>, current: Int, target: Int): Boolean {
        val queue: Queue<Int> = LinkedList()
        val visited = mutableSetOf<Int>()
        queue.offer(current)
        visited.add(current)
        while (queue.isNotEmpty()) {
            for (i in queue.indices) {
                val node = queue.poll()
                if (node == target) return true
                graph[node]?.forEach { neighbor ->
                    if (!visited.contains(neighbor)) {
                        if (neighbor == target) return true
                        visited.add(neighbor)
                        queue.offer(neighbor)
                    }
                }
            }
        }
        return false
    }
}
時間複雜度:,其中 
 是圖中節點的數量,
 是圖中邊的數量。我們最多只需要訪問每個節點和每條邊一次,所以時間複雜度為 
。
空間複雜度:,其中 
 是圖中節點的數量,
 是圖中邊的數量。空間複雜度主要取決於三個部分:
graph、visited和 queue。 graph 需要  的空間,
visited 需要  的空間,
queue 最多需要  的空間。因此,總的空間複雜度為 
。
來,一起準備面試吧!
寫一份超級吸睛的履歷吧!從技術主管的視角,幫助你用精練語句量化成效,讓你的履歷變得更加出色
履歷諮詢
加入讀書會 (邀請碼:2573)