Question

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.

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.

Solution

If the current candidate does not exist in all words' prefix, we can stop backtracking immediately. This can be done by using a trie structure.

 public class Solution {
Set<String> result = new HashSet<String>(); public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words)
trie.insert(word);
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(board, "", i, j, trie, visited);
}
}
return new ArrayList<String>(result);
} private void dfs(char[][] board, String prev, int startX, int startY, Trie trie, boolean[][] visited) {
int m = board.length, n = board[0].length;
if (startX < 0 || startX >= m || startY < 0 || startY >= n)
return;
if (visited[startX][startY])
return;
String current = prev + board[startX][startY];
if (!trie.startsWith(current))
return;
if (trie.search(current))
result.add(current);
visited[startX][startY] = true;
dfs(board, current, startX + 1, startY, trie, visited);
dfs(board, current, startX - 1, startY, trie, visited);
dfs(board, current, startX, startY + 1, trie, visited);
dfs(board, current, startX, startY - 1, trie, visited);
visited[startX][startY] = false;
}
}

Construct Trie

 class TrieNode {
public char value;
public boolean isLeaf;
public HashMap<Character, TrieNode> children; // Initialize your data structure here.
public TrieNode(char c) {
value = c;
children = new HashMap<Character, TrieNode>();
}
} class Trie {
TrieNode root; public Trie() {
root = new TrieNode('!');
} // Inserts a word into the trie.
public void insert(String word) {
char[] wordArray = word.toCharArray();
TrieNode currentNode = root; for (int i = 0; i < wordArray.length; i++) {
char c = wordArray[i];
HashMap<Character, TrieNode> children = currentNode.children;
TrieNode node;
if (children.containsKey(c)) {
node = children.get(c);
} else {
node = new TrieNode(c);
children.put(c, node);
}
currentNode = node; if (i == wordArray.length - 1)
currentNode.isLeaf = true;
} } // Returns if the word is in the trie.
public boolean search(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
HashMap<Character, TrieNode> children = currentNode.children;
if (children.containsKey(c)) {
TrieNode node = children.get(c);
currentNode = node;
// Need to check whether it's leaf node
if (i == word.length() - 1 && !node.isLeaf)
return false;
} else {
return false;
}
}
return true;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode currentNode = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
HashMap<Character, TrieNode> children = currentNode.children;
if (children.containsKey(c)) {
TrieNode node = children.get(c);
currentNode = node;
} else {
return false;
}
}
return true;
}
}

Word Search II 解答的更多相关文章

  1. Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)

    Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...

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

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

  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. [LeetCode] 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. 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 ...

  6. 212. Word Search II

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

  7. Word Pattern II 解答

    Question Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...

  8. Word Search II

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

  9. [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 ...

随机推荐

  1. Arm Linux系统调用流程详细解析

    Linux系统通过向内核发出系统调用(system call)实现了用户态进程和硬件设备之间的大部分接口. 系统调用是操作系统提供的服务,用户程序通过各种系统调用,来引用内核提供的各种服务,系统调用的 ...

  2. 分析NTFS文件系统得到特定文件的内容

    找某一个文件的内容(如要读取文件D:\dir\dir2\text.txt,详细过程例如以下: (1)读取分区表/分区链表信息,找到磁盘F的起始扇区. (2)读取D盘的第一个扇区(分区的BOOTSETO ...

  3. [Hapi.js] Request Validation with Joi

    hapi supports request validation out of the box using the joi module. Request path parameters, paylo ...

  4. 89c52串口发送接收小示例

    //串口发送 void sendChar(char *p)//调用前关中断,调用完成后关中断 { while(*p != '\0') { SBUF = *P while(!TI); TI = 0; p ...

  5. [Python学习笔记][第五章Python函数设计与使用]

    2016/1/29学习内容 第四章 Python函数设计与使用 之前的几页忘记保存了 很伤心 变量作用域 -一个变量已在函数外定义,如果在函数内需要修改这个变量的值,并将这个赋值结果反映到函数之外,可 ...

  6. Linux远程登录

    Linux远程登录 远程登录 关闭linux的防火墙 /etc/init.d/iptables stop 启动VNC服务器 Vncserver & 然后记住desktop is localho ...

  7. HTML入门基础

    前言:学了一段时间的前端,一直没有写博客的习惯,趁着最近学校组织的实训,把知识重新梳理一遍.知识点大部分来自老师上课学习笔记. 1.HTML是什么? HTML 是用来描述网页的一种标记语言. 1)HT ...

  8. javascript操作json总结

    原文:http://www.cnblogs.com/worfdream/articles/1956449.html JSON(JavaScript Object Notation) 是一种轻量级的数据 ...

  9. aspx调用webmethod

    [WebMethod] public static string CheckLogin(string user, string pwd) { pwd = FormsAuthentication.Has ...

  10. 原来真的不会用指针[*p++]

    Describe: 有2字节字符数据,需要转换成2字节的短整型,字符数据低字节在前. Analyse: 其实就是取一下数据,移位再或一下就好了,大伙都这样想的. Ex1: 假设tmp1就是短整型,p指 ...