Skip to content

Commit f1f7933

Browse files
committed
word-search
1 parent f77974a commit f1f7933

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

word-search/jun0811.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
7+
const directions = [
8+
[0, -1],
9+
[1, 0],
10+
[-1, 0],
11+
[0, 1],
12+
];
13+
14+
var exist = function (board, word) {
15+
const cols = board[0].length; // 가로 (열 개수)
16+
const rows = board.length; // 세로 (행 개수)
17+
let res = false;
18+
19+
for (let col = 0; col < cols; col++) {
20+
for (let row = 0; row < rows; row++) {
21+
if (board[row][col] != word[0]) continue;
22+
23+
const visited = Array.from({ length: rows }, () =>
24+
Array(cols).fill(false)
25+
);
26+
if (res) break;
27+
dfs(row, col, board[row][col], visited);
28+
}
29+
}
30+
31+
function check(row, col) {
32+
if (!(row >= 0 && row < rows)) return false;
33+
if (!(col >= 0 && col < cols)) return false;
34+
return true;
35+
}
36+
37+
function dfs(row, col, str, visited) {
38+
if (str == word) {
39+
res = true;
40+
return;
41+
}
42+
if (str.length >= word.length) return;
43+
visited[row][col] = true;
44+
45+
for (const direction of directions) {
46+
const [d_r, d_c] = direction;
47+
const newCol = col + d_c;
48+
const newRow = row + d_r;
49+
50+
if (check(newRow, newCol) && !visited[newRow][newCol]) {
51+
dfs(newRow, newCol, str + board[newRow][newCol], visited);
52+
}
53+
}
54+
visited[row][col] = false;
55+
}
56+
57+
return res;
58+
};

0 commit comments

Comments
 (0)