Skip to content

Commit 6729bbe

Browse files
committed
feat: add Word Search
1 parent d034dd0 commit 6729bbe

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Roadmap: https://neetcode.io/roadmap
7676
| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/description/) | Medium | [ts](./TypeScript/39.combination-sum.ts) | Backtracking |
7777
| 90 | [Subsets II](https://leetcode.com/problems/subsets-ii/description/) | Medium | [ts](./TypeScript/90.subsets-ii.ts) | Backtracking |
7878
| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/description/) | Medium | [ts](./TypeScript/40.combination-sum-ii.ts) | Backtracking |
79+
| 79 | [Word Search](https://leetcode.com/problems/word-search/) | Medium | [ts](./TypeScript/79.word-search.ts) | Backtracking |
7980

8081
### Others
8182

TypeScript/79.word-search.ts

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
function exist(board: string[][], word: string): boolean {
2+
const rows = board.length;
3+
const cols = board[0].length;
4+
const paths = new Set<string>();
5+
6+
function backtrace(r: number, c: number, i: number) {
7+
if (i === word.length) {
8+
return true;
9+
}
10+
11+
if (
12+
r < 0 ||
13+
r >= rows ||
14+
c < 0 ||
15+
c >= cols ||
16+
board[r][c] !== word[i] ||
17+
paths.has(`${r}, ${c}`)
18+
) {
19+
return false;
20+
}
21+
22+
paths.add(`${r}, ${c}`);
23+
const result =
24+
backtrace(r + 1, c, i + 1) ||
25+
backtrace(r - 1, c, i + 1) ||
26+
backtrace(r, c + 1, i + 1) ||
27+
backtrace(r, c - 1, i + 1);
28+
paths.delete(`${r}, ${c}`);
29+
30+
return result;
31+
}
32+
33+
for (let i = 0; i < rows; i++) {
34+
for (let j = 0; j < cols; j++) {
35+
if (backtrace(i, j, 0)) {
36+
return true;
37+
}
38+
}
39+
}
40+
41+
return false;
42+
}
43+
44+
console.log(
45+
exist(
46+
[
47+
["A", "B", "C", "E"],
48+
["S", "F", "C", "S"],
49+
["A", "D", "E", "E"],
50+
],
51+
"ABCCED"
52+
)
53+
);
54+
console.log(
55+
exist(
56+
[
57+
["A", "B", "C", "E"],
58+
["S", "F", "C", "S"],
59+
["A", "D", "E", "E"],
60+
],
61+
"SEE"
62+
)
63+
);

0 commit comments

Comments
 (0)