题目:

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]

Return ["eat","oath"].

Note:
You may assume that all inputs are consist of lowercase letters a-z.

click to show hint.

You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?

If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.

链接: http://leetcode.com/problems/word-search-ii/

题解:

使用Word Search的方法会超时。因为对每一个word我们都要对整个board进行一遍dfs,所以对于每个单词我们的Time Complexity - O(mn * 26L),大集合的话时间会很长,所以不能用这个方法。

据提示我们尝试使用Tire来做。用words里所有的word先建立好Trie,然后再用DFS扫描board就可以了。为什么我们要使用Trie呢?我觉得主要是因为搜索完一个单词之后,可以继续搜索下一个单词,而不用向Brute force搜索完以后要回头重新查找。举个例子,假如单词为sea,seafood,那么搜索到sea后,我们可以继续搜索seafood。 需要注意的是回溯的时候我们依然要进行剪枝操作。访问过的节点,我们和Word Search一样,先mark为"#",dfs之后再mark回来。搜索到的单词,我们可以把isWord设为false,这样可以处理duplicate。这道题目值得好好理解,整理思路。最近做的一些题目都是动不动就要70+ 行, 希望努力修炼能够有所进步,思维和coding能力。

Time Complexity - O(mn * 26L), Space Complexity - O(26L)       <<- 复杂度二刷的时候还要好好分析

public class Solution {
private TrieNode root; private class TrieNode {
private final int R = 26; // Radix R = 26
public boolean isWord;
public TrieNode[] next; public TrieNode() {
next = new TrieNode[R];
}
} public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
if(board == null || board.length == 0)
return res;
root = new TrieNode(); for(String word : words) // build Trie
addWords(word); StringBuilder sb = new StringBuilder(); // try assemble word for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
search(res, sb, root, board, i, j);
}
} return res;
} private void addWords(String word) {
if(word == null || word.length() == 0)
return;
int d = 0;
TrieNode node = root; while(d < word.length()) {
char c = word.charAt(d);
if(node.next[c - 'a'] == null)
node.next[c - 'a'] = new TrieNode();
node = node.next[c - 'a'];
d++;
} node.isWord = true;
} private void search(List<String> res, StringBuilder sb, TrieNode node, char[][] board, int i, int j) {
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length)
return;
if(board[i][j] == '#') // pruning
return;
char c = board[i][j]; TrieNode curRoot = node.next[c - 'a']; // set node here for DFS
if(curRoot == null)
return;
sb.append(c); if(curRoot.isWord == true) {
curRoot.isWord = false;
res.add(sb.toString());
} board[i][j] = '#'; // mark visited cell to '#'
search(res, sb, curRoot, board, i + 1, j);
search(res, sb, curRoot, board, i - 1, j);
search(res, sb, curRoot, board, i, j + 1);
search(res, sb, curRoot, board, i, j - 1);
sb.setLength(sb.length() - 1);
board[i][j] = c; // backtracking
}
}

Reference:

https://leetcode.com/discuss/36411/27-lines-uses-complex-numbers

https://leetcode.com/discuss/36337/my-simple-and-clean-java-code-using-dfs-and-trie

212. Word Search II的更多相关文章

  1. leetcode 79. Word Search 、212. Word Search II

    https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...

  2. [LeetCode] 212. Word Search II 词语搜索之二

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  3. 【leetcode】212. Word Search II

    Given an m x n board of characters and a list of strings words, return all words on the board. Each ...

  4. Java for LeetCode 212 Word Search II

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  5. [LeetCode] 212. Word Search II 词语搜索 II

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  6. [LeetCode#212]Word Search II

    Problem: Given a 2D board and a list of words from the dictionary, find all words in the board. Each ...

  7. [leetcode trie]212. Word Search II

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  8. 【LeetCode】212. Word Search II 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...

  9. 79. 212. Word Search *HARD* -- 字符矩阵中查找单词

    79. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be co ...

随机推荐

  1. iOS开发基础之ivars(实例变量)与@property(属性)

    Objective-C带来了一个重大改进就是Non-fragile ivar.使得i一个类可以随意增加实例变量,不必对子类重新编译.对框架开发者(如苹果)有重大意义. 最新的编译器支持@propert ...

  2. myeclipse 的 working set

    想必大家的myeclipse会有很多工程看的和不方便,那么怎么让它看的简洁一点呢,使用working set 会让你的目录看起来没有那么的多. 首先是怎么创建 working set  ,在新建时选择 ...

  3. jquery实现视觉滚动--fullpage

    用fullpage.js实现视觉滚动效果 1.Html页面 <!DOCTYPE html> <html> <head> <meta charset=" ...

  4. C语言中格式化输出的转换说明的fldwidth和precision解析

    首先说什么是C语言的格式化输出,就是printf和它的几个变种(grep -E "v?(sn|s|f)printf").像这些函数都有一个参数format,format中可以加点转 ...

  5. html 模板 swig 预编译插件 grunt-swig-precompile

    GitHub grunt-swig-precompile NPM grunt-swig-precompile 在书写前端静态页面的时候,每个页面总在书写很多重复的标签. 为了提高效率,结合 swig. ...

  6. Android源代码编译——下载

    下了好久的源代码,真真是慢哈.真希望国内有公司能够把镜像开放出来. 不多说,首先是系统环境,我的系统是Ubuntu 64位系统(14.04), 版本应该没什么. 需要的库 Git: 没话说必须, su ...

  7. [ Windows] [ OS ] [ Remote Desktop ] 開啟同一個帳號同時2的連線RDP的方式

    感謝同事 Allen 的Support :) 執行>gpedit.msc 電腦設定>Windows元件>遠端桌面服務>遠端桌面工作階段主機>連線>限制遠端桌面服務的 ...

  8. Objective-C常用类型、对象、方法

    结构体 NSRange range=NSMakeRange(8,10);从0数第八个元素开始长度为10: NSString *str=NSStringFormRange(range); NSLog(@ ...

  9. Android的ProgressBar以及自定义进度条

    1.xml文件 activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/an ...

  10. log4net 配置

    1.在项目中引入log4net.dll组件: 2.在App.congfig中做如下修改 在加入如下内容: 这个节点最好放在<configuration>下的第一个位置,不然在服务里会报错. ...