Skip to content

Commit f14fefe

Browse files
committed
feat: Add solution for LeetCode problem 79
1 parent 5e112c3 commit f14fefe

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

word-search/WhiteHyun.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//
2+
// 79. Word Search
3+
// https://leetcode.com/problems/word-search/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/28.
7+
//
8+
9+
class Solution {
10+
func exist(_ board: [[Character]], _ word: String) -> Bool {
11+
let rows = board.count
12+
let cols = board[0].count
13+
let word = Array(word)
14+
var visited = Array(repeating: Array(repeating: false, count: cols), count: rows)
15+
16+
for row in 0 ..< rows {
17+
for col in 0 ..< cols {
18+
if board[row][col] == word[0], dfs(board, word, row, col, 0, &visited) {
19+
return true
20+
}
21+
}
22+
}
23+
24+
return false
25+
}
26+
27+
private func dfs(_ board: [[Character]], _ word: [Character], _ row: Int, _ col: Int, _ index: Int, _ visited: inout [[Bool]]) -> Bool {
28+
if index == word.count {
29+
return true
30+
}
31+
32+
if row < 0 || row >= board.count || col < 0 || col >= board[0].count || visited[row][col] || board[row][col] != word[index] {
33+
return false
34+
}
35+
36+
visited[row][col] = true
37+
38+
let directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
39+
40+
for (dx, dy) in directions {
41+
if dfs(board, word, row + dx, col + dy, index + 1, &visited) {
42+
return true
43+
}
44+
}
45+
46+
visited[row][col] = false
47+
return false
48+
}
49+
}

0 commit comments

Comments
 (0)