Skip to content

Commit 8a907ea

Browse files
committed
solve: word search
1 parent eed392a commit 8a907ea

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

word-search/tolluset.ts

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* TC: O(row * column * 4^words.length)
3+
* SC: O(n)
4+
* */
5+
function exist(board: string[][], word: string): boolean {
6+
const words = word.split("");
7+
const n = words.length;
8+
9+
const rowLen = board.length;
10+
const columnLen = board[0].length;
11+
12+
const dfs = (row: number, column: number, cursor: number) => {
13+
if (cursor === n) {
14+
return true;
15+
}
16+
17+
if (
18+
row < 0 ||
19+
row >= rowLen ||
20+
column < 0 ||
21+
column >= columnLen ||
22+
board[row][column] !== words[cursor]
23+
) {
24+
return false;
25+
}
26+
27+
const current = board[row][column];
28+
board[row][column] = "";
29+
30+
if (
31+
dfs(row - 1, column, cursor + 1) ||
32+
dfs(row + 1, column, cursor + 1) ||
33+
dfs(row, column - 1, cursor + 1) ||
34+
dfs(row, column + 1, cursor + 1)
35+
) {
36+
return true;
37+
}
38+
39+
board[row][column] = current;
40+
41+
return false;
42+
};
43+
44+
for (let row = 0; row < rowLen; row++) {
45+
for (let column = 0; column < columnLen; column++) {
46+
if (dfs(row, column, 0)) {
47+
return true;
48+
}
49+
}
50+
}
51+
52+
return false;
53+
}
54+
55+
const t1 = exist(
56+
[
57+
["A", "B", "C", "E"],
58+
["S", "F", "C", "S"],
59+
["A", "D", "E", "E"],
60+
],
61+
"ABCCED",
62+
);
63+
console.info("🚀 : tolluset.ts:5: t1=", t1); // true
64+
65+
const t2 = exist(
66+
[
67+
["A", "B", "C", "E"],
68+
["S", "F", "C", "S"],
69+
["A", "D", "E", "E"],
70+
],
71+
"SEE",
72+
);
73+
console.info("🚀 : tolluset.ts:15: t2=", t2); // true
74+
75+
const t3 = exist(
76+
[
77+
["A", "B", "C", "E"],
78+
["S", "F", "C", "S"],
79+
["A", "D", "E", "E"],
80+
],
81+
"ABCB",
82+
);
83+
console.info("🚀 : tolluset.ts:24: t3=", t3); // false

0 commit comments

Comments
 (0)