Skip to content

feat: add swift implementation to lcof problem: No.12 #2864

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
May 21, 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
60 changes: 60 additions & 0 deletions lcof/面试题12. 矩阵中的路径/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,66 @@ public class Solution {
}
```

#### Swift

```swift
class Solution {
private var board: [[Character]]
private var word: String
private var m: Int
private var n: Int

init() {
self.board = []
self.word = ""
self.m = 0
self.n = 0
}

func exist(_ board: [[Character]], _ word: String) -> Bool {
self.board = board
self.word = word
m = board.count
n = board[0].count

for i in 0..<m {
for j in 0..<n {
if dfs(i, j, 0) {
return true
}
}
}
return false
}

private func dfs(_ i: Int, _ j: Int, _ k: Int) -> Bool {
if k == word.count {
return true
}
if i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[word.index(word.startIndex, offsetBy: k)] {
return false
}

let temp = board[i][j]
board[i][j] = " "
let dirs = [-1, 0, 1, 0, -1]
var ans = false

for l in 0..<4 {
let ni = i + dirs[l]
let nj = j + dirs[l + 1]
if dfs(ni, nj, k + 1) {
ans = true
break
}
}

board[i][j] = temp
return ans
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
55 changes: 55 additions & 0 deletions lcof/面试题12. 矩阵中的路径/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class Solution {
private var board: [[Character]]
private var word: String
private var m: Int
private var n: Int

init() {
self.board = []
self.word = ""
self.m = 0
self.n = 0
}

func exist(_ board: [[Character]], _ word: String) -> Bool {
self.board = board
self.word = word
m = board.count
n = board[0].count

for i in 0..<m {
for j in 0..<n {
if dfs(i, j, 0) {
return true
}
}
}
return false
}

private func dfs(_ i: Int, _ j: Int, _ k: Int) -> Bool {
if k == word.count {
return true
}
if i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[word.index(word.startIndex, offsetBy: k)] {
return false
}

let temp = board[i][j]
board[i][j] = " "
let dirs = [-1, 0, 1, 0, -1]
var ans = false

for l in 0..<4 {
let ni = i + dirs[l]
let nj = j + dirs[l + 1]
if dfs(ni, nj, k + 1) {
ans = true
break
}
}

board[i][j] = temp
return ans
}
}
Loading