【leetcode】JS 字典树 建树 查找键 查找键前缀【模板】

var findWords = function(grid, words) {
    
    
  // 存放最终结果集
  let res = []
  // 字典树节点
  class TrieNode {
    
    
    constructor(){
    
    
      this.end = false
      this.child = {
    
    }
    }
  }
  // 最终形成的字典树根节点
  let root = null
  let Trie = function(){
    
    
    root = new TrieNode()
  }
  // 建立字典树
  Trie.prototype.insert = (word) => {
    
    
    let cur = root
    for(let i=0;i<word.length;i++){
    
    
      if(!cur.child[word[i]]){
    
    
        cur.child[word[i]] = new TrieNode()
      }
      cur = cur.child[word[i]]
    }
    cur.end = true
  }
  // 在 Trie 树中查找键
  let searchPrefix = (word) => {
    
    
    let cur = root
    for(let i=0;i<word.length;i++){
    
    
      if(cur.child[word[i]]){
    
    
        cur = cur.child[word[i]]
      }else{
    
    
        return null
      }
    }
    return cur
  }
  Trie.prototype.search = (word) => {
    
    
    let cur = searchPrefix(word)
    return cur !== null && cur.end
  }
  // 查找 Trie 树中的键前缀
  Trie.prototype.startsWith = (pre) => {
    
    
    return searchPrefix(pre) != null
  }
  // 创建根节点
  let trie = new Trie()
  // 进行建树操作
  for(let i=0;i<words.length;i++){
    
    
    trie.insert(words[i])
  }
  let dfs = (x,y,t,cur) => {
    
    
    if(cur.end){
    
    
      res.push(t)
      cur.end = false // 避免重复计算
    }
    // 剪枝条件:1.边界处理 2.下一步是否可走 3.下一步字典树是否可走
    if(x<0 || x>=grid.length || y<0 || y>=grid[0].length || grid[x][y] == '#' || !cur.child[grid[x][y]]) return
    let tmp = grid[x][y]
    grid[x][y] = '#'  // 走
    cur = cur.child[tmp]
    dfs(x+1,y,t+tmp,cur)  // 上下左右四个方向遍历
    dfs(x,y+1,t+tmp,cur)
    dfs(x-1,y,t+tmp,cur)
    dfs(x,y-1,t+tmp,cur)
    grid[x][y] = tmp // 回溯(还原)
  }
  // 对单词表进行全局搜索
  for(let i=0;i<grid.length;i++){
    
    
    for(let j=0;j<grid[0].length;j++){
    
    
      dfs(i,j,'',root)
    }
  }
  return res
};

let words = ["oath","pea","eat","rain"] 
let grid =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
console.log(findWords(grid,words)) //[ 'oath', 'eat' ]

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/108563711
今日推荐