diff --git a/lcci/04.01.Route Between Nodes/README.md b/lcci/04.01.Route Between Nodes/README.md index 902a2c745f83f..80761db27979f 100644 --- a/lcci/04.01.Route Between Nodes/README.md +++ b/lcci/04.01.Route Between Nodes/README.md @@ -180,6 +180,40 @@ function findWhetherExistsPath( } ``` +```swift +class Solution { + private var g: [[Int]]! + private var vis: [Bool]! + private var target: Int! + + func findWhetherExistsPath(_ n: Int, _ graph: [[Int]], _ start: Int, _ target: Int) -> Bool { + vis = [Bool](repeating: false, count: n) + g = [[Int]](repeating: [], count: n) + self.target = target + for e in graph { + g[e[0]].append(e[1]) + } + return dfs(start) + } + + private func dfs(_ i: Int) -> Bool { + if i == target { + return true + } + if vis[i] { + return false + } + vis[i] = true + for j in g[i] { + if dfs(j) { + return true + } + } + return false + } +} +``` + ### 方法二:BFS diff --git a/lcci/04.01.Route Between Nodes/README_EN.md b/lcci/04.01.Route Between Nodes/README_EN.md index c1b2e7c680e98..ddaa9df5d8d37 100644 --- a/lcci/04.01.Route Between Nodes/README_EN.md +++ b/lcci/04.01.Route Between Nodes/README_EN.md @@ -187,6 +187,40 @@ function findWhetherExistsPath( } ``` +```swift +class Solution { + private var g: [[Int]]! + private var vis: [Bool]! + private var target: Int! + + func findWhetherExistsPath(_ n: Int, _ graph: [[Int]], _ start: Int, _ target: Int) -> Bool { + vis = [Bool](repeating: false, count: n) + g = [[Int]](repeating: [], count: n) + self.target = target + for e in graph { + g[e[0]].append(e[1]) + } + return dfs(start) + } + + private func dfs(_ i: Int) -> Bool { + if i == target { + return true + } + if vis[i] { + return false + } + vis[i] = true + for j in g[i] { + if dfs(j) { + return true + } + } + return false + } +} +``` + ### Solution 2: BFS diff --git a/lcci/04.01.Route Between Nodes/Solution.swift b/lcci/04.01.Route Between Nodes/Solution.swift new file mode 100644 index 0000000000000..f3bcbee8fcc2e --- /dev/null +++ b/lcci/04.01.Route Between Nodes/Solution.swift @@ -0,0 +1,31 @@ +class Solution { + private var g: [[Int]]! + private var vis: [Bool]! + private var target: Int! + + func findWhetherExistsPath(_ n: Int, _ graph: [[Int]], _ start: Int, _ target: Int) -> Bool { + vis = [Bool](repeating: false, count: n) + g = [[Int]](repeating: [], count: n) + self.target = target + for e in graph { + g[e[0]].append(e[1]) + } + return dfs(start) + } + + private func dfs(_ i: Int) -> Bool { + if i == target { + return true + } + if vis[i] { + return false + } + vis[i] = true + for j in g[i] { + if dfs(j) { + return true + } + } + return false + } +}