Skip to content

Commit 1276eba

Browse files
authoredApr 24, 2024
feat: add swift implementation to lcci problem: No.04.01 (#2650)
1 parent 1f8ec5f commit 1276eba

File tree

3 files changed

+99
-0
lines changed

3 files changed

+99
-0
lines changed
 

‎lcci/04.01.Route Between Nodes/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,40 @@ function findWhetherExistsPath(
180180
}
181181
```
182182

183+
```swift
184+
class Solution {
185+
private var g: [[Int]]!
186+
private var vis: [Bool]!
187+
private var target: Int!
188+
189+
func findWhetherExistsPath(_ n: Int, _ graph: [[Int]], _ start: Int, _ target: Int) -> Bool {
190+
vis = [Bool](repeating: false, count: n)
191+
g = [[Int]](repeating: [], count: n)
192+
self.target = target
193+
for e in graph {
194+
g[e[0]].append(e[1])
195+
}
196+
return dfs(start)
197+
}
198+
199+
private func dfs(_ i: Int) -> Bool {
200+
if i == target {
201+
return true
202+
}
203+
if vis[i] {
204+
return false
205+
}
206+
vis[i] = true
207+
for j in g[i] {
208+
if dfs(j) {
209+
return true
210+
}
211+
}
212+
return false
213+
}
214+
}
215+
```
216+
183217
<!-- tabs:end -->
184218

185219
### 方法二:BFS

‎lcci/04.01.Route Between Nodes/README_EN.md

+34
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,40 @@ function findWhetherExistsPath(
187187
}
188188
```
189189

190+
```swift
191+
class Solution {
192+
private var g: [[Int]]!
193+
private var vis: [Bool]!
194+
private var target: Int!
195+
196+
func findWhetherExistsPath(_ n: Int, _ graph: [[Int]], _ start: Int, _ target: Int) -> Bool {
197+
vis = [Bool](repeating: false, count: n)
198+
g = [[Int]](repeating: [], count: n)
199+
self.target = target
200+
for e in graph {
201+
g[e[0]].append(e[1])
202+
}
203+
return dfs(start)
204+
}
205+
206+
private func dfs(_ i: Int) -> Bool {
207+
if i == target {
208+
return true
209+
}
210+
if vis[i] {
211+
return false
212+
}
213+
vis[i] = true
214+
for j in g[i] {
215+
if dfs(j) {
216+
return true
217+
}
218+
}
219+
return false
220+
}
221+
}
222+
```
223+
190224
<!-- tabs:end -->
191225

192226
### Solution 2: BFS
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
private var g: [[Int]]!
3+
private var vis: [Bool]!
4+
private var target: Int!
5+
6+
func findWhetherExistsPath(_ n: Int, _ graph: [[Int]], _ start: Int, _ target: Int) -> Bool {
7+
vis = [Bool](repeating: false, count: n)
8+
g = [[Int]](repeating: [], count: n)
9+
self.target = target
10+
for e in graph {
11+
g[e[0]].append(e[1])
12+
}
13+
return dfs(start)
14+
}
15+
16+
private func dfs(_ i: Int) -> Bool {
17+
if i == target {
18+
return true
19+
}
20+
if vis[i] {
21+
return false
22+
}
23+
vis[i] = true
24+
for j in g[i] {
25+
if dfs(j) {
26+
return true
27+
}
28+
}
29+
return false
30+
}
31+
}

0 commit comments

Comments
 (0)