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 =
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
问题描述:在一个字符矩阵中,搜索字符串,字符矩阵中的各个字符需要排列连续,即后一个在前一个字符的前、后、左、右的任一位置。
显然可以用图的DFS算法来做。
//利用深度搜索优先的思想
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
bool rst;
if(word.size()==0)
return true;
if(board.size()==0||board[0].size()==0)
return false;
vector<vector<bool>> used(board.size(),vector<bool>(board[0].size(),false));
for(int i=0;i<board.size();i++)
for(int j=0;j<board[0].size();j++){
rst=_DFSearch(i,j,board,word,0,used);
if(rst==true)
return true;
}
return false;
}
private:
bool _DFSearch(int i,int j,vector<vector<char>>& board,string word,int index,vector<vector<bool>>& used){
bool rst;
if(index==word.size())
return true;
if(i<0||i>board.size()-1||j<0||j>board[0].size()-1||used[i][j]==true||board[i][j]!=word[index])
return false;
used[i][j]=true; //该字符已被使用
rst=_DFSearch(i+1,j,board,word,index+1,used)||_DFSearch(i-1,j,board,word,index+1,used)||_DFSearch(i,j+1,board,word,index+1,used)||_DFSearch(i,j-1,board,word,index+1,used);
used[i][j]=false;
return rst;
}
};