Skip to content

Commit 974e38a

Browse files
committed
feat: 문제풀이 추가
1 parent 30f5b92 commit 974e38a

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

word-search/hwanmini.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
2+
// m은 board의 행 수, n은 board의 열 수, 4(상하좌우), l(word)
3+
4+
// 시간복잡도: O(m * n * 4L)
5+
// 공간복잡도: O(m * n + L)
6+
7+
const d_row = [1, -1, 0, 0]
8+
const d_col = [0, 0, -1, 1]
9+
10+
11+
const isMoveBoard = (new_row, new_col, board) => {
12+
return new_row >= 0 && new_row < board.length && new_col >= 0 && new_col < board[0].length
13+
}
14+
15+
16+
/**
17+
* @param {character[][]} board
18+
* @param {string} word
19+
* @return {boolean}
20+
*/
21+
var exist = function(board, word) {
22+
let result = false
23+
24+
const visited = Array.from({length: board.length} , () => Array.from({length: board[0].length}).fill(false))
25+
26+
const dfs = (strs, row, col, count) => {
27+
28+
if (strs[count] !== word[count]) return
29+
if (strs.length > word.length) return
30+
31+
if (strs === word) {
32+
result = true
33+
return
34+
}
35+
36+
for (let i = 0 ; i < d_row.length; i++) {
37+
const new_row = row + d_row[i]
38+
const new_col = col + d_col[i]
39+
40+
if (isMoveBoard(new_row, new_col, board) && visited[new_row][new_col] !== true){
41+
visited[new_row][new_col] = true
42+
dfs(strs+board[new_row][new_col], new_row, new_col, count+1)
43+
visited[new_row][new_col] = false
44+
}
45+
}
46+
47+
48+
49+
}
50+
51+
52+
for (let row = 0 ; row < board.length ; row++) {
53+
for (let col = 0 ; col < board[0].length ; col++) {
54+
visited[row][col] = true
55+
dfs(board[row][col], row, col , 0)
56+
visited[row][col] = false
57+
}
58+
}
59+
60+
61+
return result
62+
};
63+
64+
console.log(exist([["A","B","C","E"],
65+
["S","F","C","S"],
66+
["A","D","E","E"]], "ABCCED"))
67+
console.log(exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE"))
68+
console.log(exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB"))
69+

0 commit comments

Comments
 (0)