题目:

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. SVN全量备份+增量备份脚本

    一.全量备份 环境:一台主SVN,一台备SVN(主要提供备份功能),后续可通过钩子脚本进行实时备份,后续发给大家. 工作原理:通过svn的hotcopy命令过行热备份,并进行一系列的检查,备份后通过r ...

  2. thinkphp 前后版本ajaxReturn方法的分别

    之前用的是thinkphp2的版本现在改到thinkphp3.2已上的版本,发现ajaxReturn这个方法返回的数据不一样了,现在做下记录 thinkphp2的ajaxReturn的实现原码 pro ...

  3. vim ctags 的使用

    ubantu 先安装 sudo apt-get install ctags 『基本功能使用方法』常用命令列表:        1.  $ ctags –R *      ($ 为Linux系统Shel ...

  4. Git 安装与使用(二)

    一.分支管理 在Git里,master是主分支,同时可以创建其他分支,支持各分支合并到主分支上,基本命令如下 1.创建分支 git checkout -b dev       创建dev分支,并切换到 ...

  5. Jquery实现搜索框提示功能

    博客的前某一篇文章中http://www.cnblogs.com/hEnius/p/2013-07-01.html写过一个用Ajax来实现一个文本框输入的提示功能.最近在一个管理项目的项目中,使用后发 ...

  6. jquery nicescroll 配置参数

    jQuery滚动条插件兼容ie6+.手机.ipad http://www.areaaperta.com/nicescroll/ jQuery(function($){ $("#scrollI ...

  7. javascript获取ckeditor编辑器的值(实现代码)

    CKeditor编辑器是FCKeditor的升级版本想对于FCK来说,确实比较好用,加载速度也比较快以下是如果通过JS获取CKeditor编辑器的值,用于表单验证 if(CKEDITOR.instan ...

  8. 普通用户开启AUTOTRACE 功能

    AUTOTRACE是一个SQL*Plus工具,用于跟踪SQL的执行计划,收集执行时所耗用资源的统计信息.系统账户本身具有AUTOTRACE,其他账户需要通过手动赋予 一. 用系统账户登录(DBA) S ...

  9. google map api 学习笔记

    (1)地图的缩放监听函数 google.maps.event.addlistener(map,"zoom_change",function(){ 缩放级别变化后的函数. }); ( ...

  10. poj 2774 Long Long Message 后缀数组LCP理解

    题目链接 题意:给两个长度不超过1e5的字符串,问两个字符串的连续公共子串最大长度为多少? 思路:两个字符串连接之后直接后缀数组+LCP,在height中找出max同时满足一左一右即可: #inclu ...