标签:为我 dex array map continue cto 使用 child etc
一眼看出是使用回溯法。
function findWords(board, words) {
var rows = board.length, cols = board[0].length, res = []
var visited = new Array(rows).fill(0).map(function (el, i) {
return new Array(cols).fill(false)
})
var set = new Set();
for (var word of words) {
set.add(word);
}
function backtrack(cur, x, y) {
if (x == rows || x < 0 || y == cols || y < 0 || visited[x][y]) {
return;
}
var c = board[x][y];
if (set.has(cur + c)) {
res.push(cur + c);
set.delete(cur + c);
}
visited[x][y] = true;
backtrack(cur + c, x + 1, y);
backtrack(cur + c, x - 1, y);
backtrack(cur + c, x, y + 1);
backtrack(cur + c, x, y - 1);
visited[x][y] = false;
}
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
backtrack("", i, j);
}
}
return res;
}
于是超时了。因为我们没有对字符的方向进行控制,有的字符只能向上或向下,这是由words数组里面的单词决定的。因此我们可以弄一个前缀树,这样我们就能找到字符间的流向了。
function Node(value) {
this.value = value
this.word = null
this.children = new Array(26)
}
class Tire {
constructor() {
this.root = new Node(null)
}
addWord(word) {
var node = this.root;
for (var c of word) {
var index = c.charCodeAt(0) - 97
if (!node.children[index]) {
node.children[index] = new Node(c)
}
node = node.children[index]
}
node.word = word
}
}
function findWords(board, words) {
var rows = board.length, cols = board[0].length;
var visited = new Array(rows).fill(0).map(function (el, i) {
return new Array(cols).fill(false)
})
var trie = new Tire()
for (let word of words) {
trie.addWord(word)
}
var root = trie.root, res = []
//用于简洁地取得下一个trie节点
function getChild(root, i, j) {
return root.children[board[i][j].charCodeAt(0) - 97]
}
function backtrack(node, x, y) {
if (x == rows || x < 0 || y == cols || y < 0 || visited[x][y]) {
return;
}
var child = getChild(node, x, y)
if (!child) {
return
}
if (child.word !== null) {
res.push(child.word);
child.word = null
}
visited[x][y] = true;
backtrack(child, x + 1, y);
backtrack(child, x - 1, y);
backtrack(child, x, y + 1);
backtrack(child, x, y - 1);
visited[x][y] = false;
}
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
if (getChild(root, i, j) == null) {
continue
}
backtrack(root, i, j)
}
}
return res;
}
标签:为我 dex array map continue cto 使用 child etc
原文地址:https://www.cnblogs.com/rubylouvre/p/12105069.html