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. 低于0.01%的极致Crash率是怎么做到的?

    WeTest 导读 看似系统Bug的Crash 99%都不是系统问题!本文将与你一起探索Crash分析的科学方法. 在移动互联网闯荡多年的iOS手机管家,经过不断迭代创新,已经涵盖了隐私(加密相册). ...

  2. Qt-QML-Charts-ChartView-编译错误-ASSERT: "!"No style available without QApplication!

    昨天本来是回家想好好琢磨一下使用Chart来绘制曲线的,奈何在建立项目的时候也就卡住了,加上心情比较烦躁,也没有耐心寻找答案就草草了事.所以今天继续搞定这个. 上图是Qt 的编译错误截图 QML de ...

  3. RabbitMQ基础教程之Spring&JavaConfig使用篇

    RabbitMQ基础教程之Spring使用篇 相关博文,推荐查看: RabbitMq基础教程之安装与测试 RabbitMq基础教程之基本概念 RabbitMQ基础教程之基本使用篇 RabbitMQ基础 ...

  4. python基础之变量和简单数据类型

    1.1 变量的命名和使用规范 变量名可以包含数字.字母.下划线,但是不能以数字开头. 变量名不能包含空格,可使用下划线来分割其中的单词. 不要将Python关键字和函数名用作变量名. 变量名应既简短又 ...

  5. JSON.parse() 与 eval()

    JSON(JavaScript Object Notation)是一种轻量级的数据格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是Javascript原生格式,这意味着在ja ...

  6. 【转】: 《江湖X》开发笔谈 - 热更新框架

    前言 大家好,我们这期继续借着我们工作室正在运营的在线游戏<江湖X>来谈一下热更新机制以及我们的理解和解决方案.这里先简单的介绍一下热更新的概念,熟悉这部分的朋友可以跳过,直接看我们的方案 ...

  7. 水仙花数---基于python

    # coding:utf-8"""水仙花数是指一个 n 位数(n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153) ...

  8. Thunder团队第一周 - Scrum会议5

    本节内容: 工作照片 会议时间 会议地点 会议内容 Todo list 燃尽图 Scrum会议5 小组名称:Thunder 项目名称:爱阅app Scrum Master:邹双黛 工作照片: 参会成员 ...

  9. lintcode-189-丢失的第一个正整数

    189-丢失的第一个正整数 给出一个无序的正数数组,找出其中没有出现的最小正整数. 样例 如果给出 [1,2,0], return 3 如果给出 [3,4,-1,1], return 2 挑战 只允许 ...

  10. iOS-根据两个经纬度计算相距距离

    CLLocation *orig=[[[CLLocation alloc] initWithLatitude:[mainDelegate.latitude_self doubleValue] long ...