79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can 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.

For example,
Given board =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

class Solution {
public:
int d[][] = {{, }, {-, }, {, }, {, -}}; bool isValid(int m, int n, int x, int y)
{
return x >= && x < m && y >= && y < n;
} bool check(vector<vector<char>>& board, string word, int m, int n, int x, int y, int l, int k)
{
if(k == l)
return true;
if(!isValid(m, n, x, y) || board[x][y] != word[k])
return false;
int tx, ty, i, j;
board[x][y] = '\0';
for(i = ; i < ; i++)
{
tx = x + d[i][];
ty = y + d[i][];
if(check(board, word, m, n, tx, ty, l, k+))
return true;
}
board[x][y] = word[k];
return false;
} bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), l = word.length();
if( == m || == l)
return false;
int n = board[].size(), i, j;
for(i = ; i < m; i++)
{
for(j = ; j < n; j++)
{
if(check(board, word, m, n, i, j, l, ))
return true;
}
}
return false;
}
};

212. Word Search II

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.

class Solution {
public:
int dir[][] = { {,},{-,},{,},{,-} }; class Node
{
public:
Node* ch[];
bool isWord;
string word;
Node()
{
memset(ch, , sizeof(ch));
isWord = false;
word = "";
}
}; void createTree(vector<string>& words, Node *root)
{
int n = words.size(), i;
for (i = ; i < n; i++)
{
Node *p = root;
for (int j = ; j < words[i].length(); j++)
{
if (p->ch[words[i][j] - 'a'] == NULL)
{
Node *t = new Node();
p->ch[words[i][j] - 'a'] = t;
}
p = p->ch[words[i][j] - 'a'];
}
p->isWord = true;
p->word = words[i];
}
} void find(vector<vector<char>>& board, Node *node, int x, int y, vector<string>& ans)
{
int n = board.size(), m = board[].size();
if (x < || x >= n || y < || y >= m || board[x][y] == '\0')
return;
if (node->ch[board[x][y] - 'a'])
node = node->ch[board[x][y] - 'a'];
else
return;
if (true == node->isWord)
{
ans.push_back(node->word);
node->isWord = false;
}
char c = board[x][y];
board[x][y] = '\0';
for (int i = ; i < ; i++)
{
int tx = x + dir[i][], ty = y + dir[i][];
find(board, node, tx, ty, ans);
}
board[x][y] = c;
} vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
{
vector<string> ans;
int n = board.size();
if (n <= )
return ans;
Node *root = new Node();
createTree(words, root);
for (int i = ; i < n; i++)
{
for (int j = ; j < board[].size(); j++)
{
find(board, root, i, j, ans);
}
}
return ans;
}
};

79. 212. Word Search *HARD* -- 字符矩阵中查找单词的更多相关文章

  1. 79. Word Search在字母矩阵中查找单词

    [抄题]: Given a 2D board and a word, find if the word exists in the grid. The word can be constructed ...

  2. word search(二维数组中查找单词(匹配字符串))

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

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

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

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

  7. 【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 ...

  8. 212. Word Search II

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

  9. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

随机推荐

  1. jquery之clone()方法详解

    clone()函数用于克隆当前匹配元素集合的一个副本,并以jQuery对象的形式返回.你也可以简单地理解为:克隆当前jQuery对象. 你还可以指定是否复制这些匹配元素(甚至它们的子元素)的附加数据( ...

  2. CSS在线字体库,外部字体的引用方法

    目录: 1:CSS家族五大字体 2:360和谷歌外部字体引用方法 3:谷歌外部字体引用方法详解 4:@font-face用法详解 一: {font-family:serif,sans-serif,fa ...

  3. An Example of Pre-Query and Post-Query Triggers in Oracle Forms With Using Display_Item to Highlight Dynamically

    Example is given for Pre-Query and Post-Query triggers in Oracle Forms, with using Display_Itembuilt ...

  4. lncRNA研究

    ------------------------------- Long noncoding RNAs are rarely translated in two human cell lines. ( ...

  5. poj 1265 Area (Pick定理+求面积)

    链接:http://poj.org/problem?id=1265 Area Time Limit: 1000MS   Memory Limit: 10000K Total Submissions:  ...

  6. Python基础学习笔记(九)常用数据类型转换函数

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-variable-types.html 3. http://www ...

  7. iOS - OC 面向对象语法

    1.类 1)根类:因为类 NSObject 是层次结构的最顶层,因此称为根类. 可以将类称为子类(subclass)和父类(superclass),也可以将类称为子类和超类. 2)分类/类别(cate ...

  8. Nginx基础知识之————Nginx 环境的搭建?

    本课时主要给大家讲解如何在 Linux 系统下搭建 Nginx 和 Nginx 搭建过程中常见问题的知识,并结合实例让学员掌握 Nginx 环境的搭建. 下载解压: 安装gcc-c++ 从新配置文件: ...

  9. [转发] 理解 oauth 2.0

    原文: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html oauth 的各种编程语言实现: http://oauth.net/2/ 理解OAu ...

  10. 理解odbc

    1.解决什么样的问题?不同的数据库产品,具有不同的特性,也就是方言.因此应用程序针对不同的数据库产品,编写不同的代码.如果换了一个数据库产品,还需要重新编写数据库交互部分,不具备扩展和移植.odbc对 ...