码迷,mamicode.com
首页 > 其他好文 > 详细

Word Search II

时间:2019-12-21 11:45:03      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:public   red   hash   class   oid   索引   key   use   search   

Given a matrix of lower alphabets and a dictionary. Find all words in the dictionary that can be found in the matrix. A word can start from any position in the matrix and go left/right/up/down to the adjacent position. One character only be used once in one word. No same word in dictionary

Example

Example 1:

Input:["doaf","agai","dcan"],["dog","dad","dgdg","can","again"]
Output:["again","can","dad","dog"]
Explanation:
  d o a f
  a g a i
  d c a n
search in Matrix,so return ["again","can","dad","dog"].

Example 2:

Input:["a"],["b"]
Output:[]
Explanation:
 a
search in Matrix,return [].

Challenge

Using trie to implement your algorithm.

 

使用了 Trie 的版本
考点:

  • 字典树
  • dfs
  • tip:Tire树,一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。

题解:

    • 首先建立字典树,字典树从root开始,每个节点利用hashmap动态开点,利用字母的公共前缀建树。
    • 遍历字母矩阵,将字母矩阵的每个字母,从root开始dfs搜索,搜索到底部时,将字符串存入答案返回即可。
      class TrieNode {    		//定义字典树的节点
          String word;
          HashMap<Character, TrieNode> children;   //使用HashMap动态开节点
          public TrieNode() {
              word = null;
              children = new HashMap<Character, TrieNode>();
          }
      };
      
      
      class TrieTree{
          TrieNode root;
          
          public TrieTree(TrieNode TrieNode) {
              root = TrieNode;
          }
          
          public void insert(String word) {		//字典树插入单词
              TrieNode node = root;
              for (int i = 0; i < word.length(); i++) {		
                  if (!node.children.containsKey(word.charAt(i))) {
                      node.children.put(word.charAt(i), new TrieNode());
                  }
                  node = node.children.get(word.charAt(i));
              }
              node.word = word;
          }
      };
      
      public class Solution {
          /**
           * @param board: A list of lists of character
           * @param words: A list of string
           * @return: A list of string
           */
          public int[] dx = {1, 0, -1, 0};   //搜索方向
          public int[] dy = {0, 1, 0, -1};
          
          public void search(char[][] board,			//在字典树上dfs查找
                             int x,
                             int y,
                             TrieNode root,
                             List<String> results) {
              if (!root.children.containsKey(board[x][y])) {
                  return;
              }
              
              TrieNode child = root.children.get(board[x][y]);
              
              if (child.word != null) {      //如果访问到字典树叶子,将字符串压入result即可
                  if (!results.contains(child.word)) {
                      results.add(child.word);
                  }
              }
              
              char tmp = board[x][y];
              board[x][y] = 0;  // mark board[x][y] as used
              
              for (int i = 0; i < 4; i++) {      //向四个方向dfs搜索
                  if (!isValid(board, x + dx[i], y + dy[i])) {
                      continue;
                  }
                  search(board, x + dx[i], y + dy[i], child, results);
              }
              
              board[x][y] = tmp;  // revert the mark
          }
          
          private boolean isValid(char[][] board, int x, int y) {     //检测搜索位置合法
              if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) {
                  return false;
              }
              
              return board[x][y] != 0;
          }
          
          public List<String> wordSearchII(char[][] board, List<String> words) {
              List<String> results = new ArrayList<String>();
              
              TrieTree tree = new TrieTree(new TrieNode());
              for (String word : words){
                  tree.insert(word);
              }
              
              for (int i = 0; i < board.length; i++) {				//遍历字母矩阵,将每个字母作为单词首字母开始搜索
                  for (int j = 0; j < board[i].length; j++) {
                      search(board, i, j, tree.root, results);
                  }
              }
              
              return results;
          }
      }
      

        

Word Search II

标签:public   red   hash   class   oid   索引   key   use   search   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12076347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!