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. gitlab-登录账户遇到ERROR: Permission to XXX.git denied to user报错怎么办

    碰到这个问题就意味着没有访问账户的权限,没有把访问电脑与访问账户用ssh_key关联起来,解决流程: 1.查看本地是否有ssh_key 笔者用的是git bash来输入命令 ls -al ~/.ssh ...

  2. leetcode-零钱兑换—int溢出

     零钱兑换 给定不同面额的硬币 coins 和一个总金额 amount.编写一个函数来计算可以凑成总金额所需的最少的硬币个数.如果没有任何一种硬币组合能组成总金额,返回 -1. 示例 1: 输入: c ...

  3. 使用open live writee写的博客

    1. 安装包 下载链接:open live writer 2. 安装及使用教程 学习教程(转载他人) 3. 插入个图片 4. 写段代码 写不了,插件用不了 5. 插件使用: 参考文章:(http:// ...

  4. idea clion编译器

    RNMV64P0LA-eyJsaWNlbnNlSWQiOiJSTk1WNjRQMExBIiwibGljZW5zZWVOYW1lIjoiY24gdHUiLCJhc3NpZ25lZU5hbWUiOiIiL ...

  5. [原创]Docker学习记录: Shipyard+Swarm+Consul+Service Discover 搭建教程

    网上乱七八糟的资料实在是太多了, 乱, 特别乱, 而看书呢, 我读了2本书, 一本叫做<>, 另一本叫做<< Docker进阶与实战>> 在 服务发现这块讲的又不清 ...

  6. Java内存管理特点

    Java内存管理特点     Java一个最大的优点就是取消了指针,由垃圾收集器来自动管理内存的回收.程序员不需要通过调用函数来释放内存. 1.Java的内存管理就是对象的分配和释放问题.     在 ...

  7. str和repr

    在Python2.6和Python3.0以及更早的版本中,在交互式模式下的输出本质上是使用repr,因此对于一些浮点数运算,会显示很多位: 4 / 5.0 #0.8000000000000004 但是 ...

  8. su和sudo的使用

    用于用户身份切换 一.su 命令形式 代表内容 su 切换为root,以non-login shell的方式 su - 切换为root,以login shell的方式 su -l 账号 切换为“账号” ...

  9. Thunder团队第一周 - Scrum会议4

    Scrum会议4 小组名称:Thunder 项目名称:爱阅app Scrum Master:代秋彤 工作照片: 参会成员: 王航:http://www.cnblogs.com/wangh013/ 李传 ...

  10. JavaWeb基础 - 会话

    会话概述 什么是会话 简单的理解:用户打开浏览器,点击多个超链接,访问Web服务器上多个资源,然后关闭浏览器,整个过程称之为一次会话. 需要解决的问题 每个用户在使用浏览器与服务器会话的过程中,会产生 ...