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 =

[
["ABCE"],
["SFCS"],
["ADEE"]
]

word ="ABCCED", -> returnstrue,
word ="SEE", -> returnstrue,
word ="ABCB", -> returnsfalse.

题意:从一个二维矩阵中找到给定单词,某个单词的下一个字符,只能从其上下左右中寻找。

思路:刚开始想到用广搜,但是,因为单词的首字符在二维数组中可能有不止一个与其对应,不合适,所以正确合适的开启方式是DFS。后来再一想,这题和surrounded regions类似,用DFS对当前位置的上下左右进行深搜,若和单词中的下一个字符相等,则从单词的下一个位置开始,重新搜索。因为题总要求,在某一次的搜索过程中,字符只能使用一次,所以对搜索过的字符要设置标识符标识已经访问过了。设置标识符有两种方法一种是:将访问过的字符设置为其他的字符,如'#',等这次搜索返回时要将其恢复到原来的字符;二是,开辟一个和元素组等大小的二维数组,标识某个字符是否被访问过,不过还是得恢复。

参考JustDoIT,代码一:

 class Solution {
public:
bool exist(vector<vector<char> > &board, string word)
{
if(word.size()==) return true;
int row=board.size(),col=board[].size();
if(row==||col==) return false; for(int i=;i<row;++i)
{
for(int j=;j<col;++j)
{
if(board[i][j]==word[]&&dfs(i,j,word,,board))
return true;
}
}
return false;
}
bool dfs(int row,int col,string &word,int index,vector<vector<char>> &board)
{
if(index==word.size()-) return true;
char temp=board[row][col]; board[row][col]='#';
if(row>&&board[row-][col]==word[index+])
if(dfs(row-,col,word,index+,board))
return true; if(row<board.size()-&&board[row+][col]==word[index+])
if(dfs(row+,col,word,index+,board))
return true; if(col>&&board[row][col-]==word[index+1])
if(dfs(row,col-,word,index+,board))
return true; if(col<board[].size()-&&board[row][col+]==word[index+])
if(dfs(row,col+,word,index+,board))
return true; board[row][col]=temp;
return false; }
};

参考Grandyang代码二:通过使用二维标识数组来实现,但要避免使用vector<bool>,原因见这里。代码见下:

 class Solution {
public:
bool exist(vector<vector<char> > &board, string word)
{
if(word.empty()) return true;
if(board.empty()||board[].empty()) return false; //bool型的数组
vector<vector<bool>> visited(board.size(),vector<bool>(board[].size(),false));
for(int i=;i<board.size();++i)
for(int j=;j<board[i].size();++j)
{
if(search(board,word,,i,j,visited))
return true;
}
return false;
} bool search(vector<vector<char>> &board,string word,int idx,int i,int j,
vector<vector<bool>> &visited)
{
if(idx==word.size()) return true;
if(i<||j<||i>=board.size()||j>=board[].size()||visited[i][j]||
board[i][j] !=word[idx])
return false; visited[i][j]=true;
bool res=search(board,word,idx+,i-,j,visited)
||search(board,word,idx+,i+,j,visited)
||search(board,word,idx+,i,j-,visited)
||search(board,word,idx+,i,j+,visited); //重置,是因为一下一个元素为起点的遍历可以重新访问上节点访问过的
visited[i][j]=false;
return res;
}
};

针对第一方法用第二方法的形式简化,代码如下:

 class Solution {
public:
bool exist(vector<vector<char> > &board, string word)
{ if(word.size()==) return true;
int row=board.size(),col=board[].size();
if(row==||col==) return false; for(int i=;i<row;++i)
{
for(int j=;j<col;++j)
{
if(board[i][j]==word[]&&dfs(i,j,word,,board))
return true;
}
}
return false;
}
bool dfs(int row,int col,string &word,int index,vector<vector<char>> &board)
{
if(index==word.size()) return true;
char temp=board[row][col]; if(row<||row>=board.size()||col<||col>=board[].size()||board[row][col] =='#'
||board[row][col] !=word[index])
return false; board[row][col]='#';
bool res=dfs(row-,col,word,index+,board)
||dfs(row+,col,word,index+,board)
||dfs(row,col-,word,index+,board)
||dfs(row,col+,word,index+,board); board[row][col]=temp;
return res;
}
};

注意方法一和方法二的下标范围

[Leetcode] word search 单词查询的更多相关文章

  1. [LeetCode] 79. Word Search 单词搜索

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

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

  3. [LeetCode] Word Search 词语搜索

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

  4. Leetcode: word search

    July 6, 2015 Problem statement: Word Search Given a 2D board and a word, find if the word exists in ...

  5. LeetCode: Word Search 解题报告

    Word SearchGiven a 2D board and a word, find if the word exists in the grid. The word can be constru ...

  6. LeetCode 79. Word Search单词搜索 (C++)

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

  7. [LeetCode] Word Squares 单词平方

    Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...

  8. [LeetCode] Word Frequency 单词频率

    Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity ...

  9. [LeetCode] Word Abbreviation 单词缩写

    Given an array of n distinct non-empty strings, you need to generate minimal possible abbreviations ...

随机推荐

  1. WSL跑linux服务程序

    前段时间折腾了一次WSL下的Apache,无奈遇到各种奇葩问题,总是解决不了,最终放弃,甚至得出了一个现在看来比较可笑的结论:WSL是不可能跑Linux服务程序的! 当时的思路想歪了,由于Apache ...

  2. Use GitHub Desktop to get GitHub projects

    Find the project's https git file in the home page of the project. e.g. https://github.com/PrismLibr ...

  3. uvaoj455Periodic Strings(枚举)

    A character string is said to have period k if it can be formed by concatenating one or more repetit ...

  4. Selenium(Python)生成Html测试报告

    由于Python3已经不支持HTMLTestRunner了, 无论是PyCharm还是pip都无法安装成功, 所以只能去 http://tungwaiyip.info/software/HTMLTes ...

  5. Javascript打印网页局部的实现方案

    项目中,需要对页面的部分div进行打印,为了保证界面布局不乱,采取了新建iframe的方法. 将需要打印的div放到iframe中,然后调用iframe进行打印,就可以很好的实现局部打印的效果了. 同 ...

  6. mysql bin log配置及查看

    mysql执行sql可以通过设置mysql bin 日志进行记录查看   mysql bin日志配置如下:   log_bin:on log_bin_basename:bin文件路径及名前缀(/var ...

  7. LeetCode 240——搜索二维矩阵 II

    1. 题目 2. 解答 2.1. 方法一 从矩阵的左下角开始比较 目标值等于当前元素,返回 true: 目标值大于当前元素,j 增 1,向右查找,排除掉此列上边的数据(都比当前元素更小): 目标值小于 ...

  8. POJ 2069 Super Star(计算几何の最小球包含+模拟退火)

    Description During a voyage of the starship Hakodate-maru (see Problem 1406), researchers found stra ...

  9. hosts_allow配置了却不生效

    hosts_allow配置了却不生效 配置了两台白名单的机器,一台生效一台不生效,google后的结果都是更新libwrap.so  安装openssh等等..(问题还是没有解决) 经过对比发现,原来 ...

  10. apache访问403错误

    1.排查selinux 2.目录权限 3.WEB主目录是否正确