Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4f5fbd4

Browse files
committed
feat: 单词搜索
1 parent d1bad23 commit 4f5fbd4

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

递归与回溯/单词搜索-79.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
let directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] // 左 右 上 下
7+
8+
let exist = function (board, word) {
9+
let maxY = board.length
10+
if (!maxY) return false
11+
let maxX = board[0].length
12+
13+
// 二维数组记录已访问过的元素
14+
let visited = new Array(maxY)
15+
for (let y = 0; y < visited.length; y++) {
16+
visited[y] = new Array(maxX)
17+
}
18+
19+
let inArea = (x, y) => {
20+
return x >= 0 && x < maxX && y >= 0 && y < maxY
21+
}
22+
23+
let search = (startX, startY, wordIndex) => {
24+
// 当前起始字符不匹配 直接失败
25+
let curCell = board[startY][startX]
26+
let curChar = word[wordIndex]
27+
if (curCell !== curChar) {
28+
return false
29+
}
30+
31+
// 如果递归到最后一位字符 就直接返回最后一位字符是否匹配成功
32+
if (wordIndex === word.length - 1) {
33+
return curChar === curChar
34+
}
35+
36+
// 进一步递归 先记录为已访问元素 防止递归的时候重复访问
37+
visited[startY][startX] = true
38+
39+
for (let direction of directions) {
40+
let [x, y] = direction
41+
let nextX = startX + x
42+
let nextY = startY + y
43+
44+
// 需要保证未越界且未被访问过
45+
if (inArea(nextX, nextY) && !visited[nextY][nextX]) {
46+
if (search(nextX, nextY, wordIndex + 1)) {
47+
return true
48+
}
49+
}
50+
}
51+
// 重置已访问标记位
52+
visited[startY][startX] = false
53+
}
54+
55+
for (let y = 0; y < maxY; y++) {
56+
for (let x = 0; x < maxX; x++) {
57+
if (search(x, y, 0)) {
58+
return true
59+
}
60+
}
61+
}
62+
63+
return false
64+
};

0 commit comments

Comments
 (0)