Skip to content

Commit f484092

Browse files
committed
solve: word search
1 parent 1be492a commit f484092

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

word-search/JustHm.swift

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// time: O(N * M * 4^L) space: O(N * M + L)
2+
// N 행 - M 열 - L word의 길이 (4방향을 탐색하기에 4^L)
3+
class Solution {
4+
func exist(_ board: [[Character]], _ word: String) -> Bool {
5+
let words = Array(word)
6+
var visited = Array(repeating: Array(repeating: false, count: board[0].count), count: board.count)
7+
var startPoints = [(Int, Int)]()
8+
// 먼저 시작 가능한 인덱스들 찾기 - O(n^2)
9+
for i in board.indices {
10+
for j in board[0].indices {
11+
if board[i][j] == words[0] {
12+
startPoints.append((i,j))
13+
}
14+
}
15+
}
16+
// 문자 찾아가기위한 DFS 내부함수 (backtracking)
17+
func dfs(_ row: Int, _ col: Int, _ index: Int) -> Bool {
18+
if row < 0 || col < 0 || row >= board.count || col >= board[0].count { return false }
19+
if visited[row][col] { return false }
20+
if board[row][col] != words[index] { return false }
21+
if index + 1 == word.count { return true }
22+
23+
visited[row][col] = true
24+
25+
for dir in [(0, 1), (1, 0), (0, -1), (-1, 0)] {
26+
let nextRow = row + dir.0
27+
let nextCol = col + dir.1
28+
if dfs(nextRow, nextCol, index + 1) {
29+
return true
30+
}
31+
}
32+
33+
visited[row][col] = false
34+
return false
35+
}
36+
// 문자 찾기
37+
for pos in startPoints {
38+
if dfs(pos.0, pos.1, 0) { return true }
39+
}
40+
return false
41+
}
42+
}

0 commit comments

Comments
 (0)