Skip to content

Commit 46cebfe

Browse files
committed
Word Search
1 parent d57a0b1 commit 46cebfe

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

word-search/casentino.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
function exist(board: string[][], word: string): boolean {
2+
const m = board.length;
3+
const n = board[0].length;
4+
5+
const visited = Array.from({ length: m }, () => new Array(n).fill(0));
6+
function findDirection(currentI: number, currentJ: number, findNextIdx: number) {
7+
if (findNextIdx === word.length) {
8+
return true;
9+
}
10+
if (
11+
currentI < 0 ||
12+
currentJ < 0 ||
13+
currentI >= m ||
14+
currentJ >= n ||
15+
board[currentI][currentJ] !== word[findNextIdx]
16+
) {
17+
return false;
18+
}
19+
if (visited[currentI][currentJ] === 1) {
20+
return false;
21+
}
22+
visited[currentI][currentJ] = 1;
23+
24+
const isApproachLastWord =
25+
findDirection(currentI + 1, currentJ, findNextIdx + 1) ||
26+
findDirection(currentI - 1, currentJ, findNextIdx + 1) ||
27+
findDirection(currentI, currentJ - 1, findNextIdx + 1) ||
28+
findDirection(currentI, currentJ + 1, findNextIdx + 1);
29+
30+
if (!isApproachLastWord) {
31+
visited[currentI][currentJ] = 0;
32+
}
33+
return isApproachLastWord;
34+
}
35+
for (let i = 0; i < m; i++) {
36+
for (let j = 0; j < n; j++) {
37+
const result = findDirection(i, j, 0);
38+
if (result) {
39+
return true;
40+
}
41+
}
42+
}
43+
return false;
44+
}

0 commit comments

Comments
 (0)