Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions lcci/04.01.Route Between Nodes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
```

<!-- tabs:end -->

### 方法二:BFS
Expand Down
34 changes: 34 additions & 0 deletions lcci/04.01.Route Between Nodes/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
```

<!-- tabs:end -->

### Solution 2: BFS
Expand Down
31 changes: 31 additions & 0 deletions lcci/04.01.Route Between Nodes/Solution.swift
Original file line number Diff line number Diff line change
@@ -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
}
}