Skip to content

feat: add swift implementation to lcci problem: No.04.01 #2650

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 24, 2024
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
}
}
Loading