[Leetcode] 79. Word Search β
Problem β
보λνμ μνλ²³μ μ΄μ΄κ°λ©΄μ μ΄μ©νμ¬ word λ₯Ό λ§λ€κΈ°
Solution β
보λνμ μνλ²³μ νλ²μ©λ§ μ¬μ©νμ¬ μΈμ ν μνλ²³μ λΆμ΄λκ°λ©΄μ word
λ₯Ό λ§λ€μ΄λ΄λ λ¬Έμ .
- DFS ν¨μλ₯Ό μμ±
- νκ²μ λ§λ¬μλ DFS νμΆ μ‘°κ±΄κ³Ό νμ λ²μλ₯Ό μ΄κ³Όνμλ 쑰건μ μ΄μ©νμ¬ κ°μ§μΉκΈ°νλ€.
- μ λ΅μ μ°Ύμμλ μ±κ³΅ μ¬λΆλ₯Ό νμ νμκΈ° λλ¬Έμ λͺ¨λ ν¨μ μ€νμ μ’ λ£νλλ‘νλ€.
- νμ¬ κΈΈμ΄κ°
word
μ λ¬Έμμ΄ κΈΈμ΄λ₯Ό μ΄κ³Όνμμλ μ€νμ μ’ λ£νλ€. - λ€μ μΈλ±μ€κ° 보λνμ λ²μλ₯Ό λ²μ΄λμ§ μλλ‘νλ€.
- μ΄λ―Έ νλ² μ¬μ©ν μνλ²³μ μ¬μ©νμ§ λͺ»νλλ‘νλ€.
word
λ₯Ό λ§λλλ° νμν μνλ²³μΈμ§ νμΈνλ€.
- μ¬μ©μ¬λΆμ 체ν¬λ DFSκ° μ€νμ΄ μ’ λ£λλ μμ μμ μ΄μ depthμ ν¨μμκ² λλ €μ€μΌνλ€.
- DFSμ μ΅μ΄ μ€ν 쑰건μ
word
μ μκΈμμ λμΌνμ§ μ‘°κ±΄μ μΆκ°νμ¬ μλλ₯Ό κ°μ νλ€.
TS Code β
ts
function exist(board: string[][], word: string): boolean {
let answer = false
const dirs = [
[1, 0],
[0, 1],
[-1, 0],
[0, -1],
]
const visited = Array.from(Array(board.length), (_, i): boolean[] => Array(board[i].length).fill(false))
const DFS = (y: number, x: number, str: string) => {
if (answer) return
if (word.length < str.length) return
if (word === str) {
answer = true
return
}
for (const [dy, dx] of dirs) {
const ty = dy + y
const tx = dx + x
if (0 <= ty && ty < board.length && 0 <= tx && tx < board[ty].length) {
if (visited[ty][tx]) continue
const c = board[ty][tx]
if (c !== word[str.length]) continue
visited[ty][tx] = true
DFS(ty, tx, str + c)
visited[ty][tx] = false
}
}
} // DFS
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
if (word[0] !== board[i][j]) continue
visited[i][j] = true
DFS(i, j, board[i][j])
visited[i][j] = false
}
}
return answer
}