题目:

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. HTML5之缓存

    ----- 缓存文件 - 使用UTF-8编码- 以Cache Manifest 开头- 三个基本部分 CACHE MANIFESTmenu.htmlmenu.js# login requires ne ...

  2. 登堂入室——java流

    ——文章出自PeterYe,不得私自转载 我所知道的 java.io里面的[流],就仿佛太平洋里面的水一样,浩浩荡荡,横无际涯... -----2016/7/16--------公寓处记录------ ...

  3. DTCMS添加文章,将tags标签的值赋到SEO关键词上,以及将摘要的值赋到SEO描述

    将tags标签的值赋到SEO关键词上 admin\article_edit.aspx中 $(function () {  方法中加上 //tags的值赋到SEO关键词上 $("#txtTag ...

  4. Delphi Idhttp Post提交 Aspx/Asp.net 时 500错误的解决办法。

    一直使用Delphi写程序,因为习惯了,用起来方便. 但是有一个问题困扰了我半年了.就是使用Idhttp Post提交时候总会有莫名其妙的错误,大部分网站没问题,但是一遇到Asp.net就报错500. ...

  5. 【Python笔记】异常处理

    1 什么是异常 异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行.一般情况下,在Python无法正常处理程序时就会发生一个异常.异常是Python对象,表示一个错误. 当Pytho ...

  6. Linux中Kill进程的N种方法

    常规篇: 首先,用ps查看进程,方法如下: $ ps -ef …… smx       1822     1  0 11:38 ?        00:00:49 gnome-terminal smx ...

  7. MVC5 Bundles发布到IIS失效问题解决方案

    MVC中Bundles可以提高代码的可重用性 我每个页面都需要用到这十几个JS+CSS 当我把MVC发布到服务器以后,Bundles中的JS和CSS会失效的时候 宝宝的心里是崩溃的.... 查了很多资 ...

  8. EXTJS 4.2 资料 控件之tabpanel 静态生成tabpanel

    //**************页面主体开始***************** var tabpanel = Ext.createWidget('tabpanel', { activeTab: 0, ...

  9. python解决汉诺塔问题

    今天刚刚在博客园安家,不知道写点什么,前两天刚刚学习完python 所以就用python写了一下汉诺塔算法,感觉还行拿出来分享一下 首先看一下描述: from :http://baike.baidu. ...

  10. 操作邮箱的类和文件的Md5【粘】

     MailMessage mailMsg = new MailMessage();//两个类,别混了,要引入System.Net这个Assembly             mailMsg.From ...