题目链接:https://leetcode.com/problems/word-search/#/description
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
.
思路:参考Number of islands
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
m=board.size();
n=board[0].size();
for(int x=0;x<m;x++)
for(int y=0;y<n;y++)
{
if(isFound(board,word.c_str(),x,y))
return true;
}
return false;
}
private:
int m;
int n;
bool isFound(vector<vector<char> > &board, const char* w, int x, int y)
{
if(x<0||y<0||x>=m||y>=n||board[x][y]=='\0'||*w!=board[x][y])
return false;
if(*(w+1)=='\0')
return true;
char t=board[x][y];
board[x][y]='\0';
if(isFound(board,w+1,x-1,y)||isFound(board,w+1,x+1,y)||isFound(board,w+1,x,y-1)||isFound(board,w+1,x,y+1))
return true;
board[x][y]=t;
return false;
}
};
class Solution{
public:
bool exist(vector<vector<char>>& board,string word)
{
if(word.length()==0)
return true;
int m=board.size(),n=board[0].size();
if(!m || !n)
return false;
if(m*n<word.length())
return false;
b=board;
w=word;
bool flag=false;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if (b[i][j]==word[0])
flag=search(i,j,b,w,0);
if(flag)
return true;
}
}
return false;
}
bool search(int i,int j,vector<vector<char>>& b,string &w,int index)
{
if(index==w.size())
return true;
if(i<0 || i==b.size() || j<0 || j==b[i].size() || b[i][j]!=w[index])
return false;
char t=b[i][j];
b[i][j]='\0';
bool down=search(i+1,j,b,w,index+1);
bool up=search(i-1,j,b,w,index+1);
bool right=search(i,j+1,b,w,index+1);
bool left=search(i,j-1,b,w,index+1);
if(up || down || left || right)
return true;
b[i][j]=t;
return false;
}
private:
vector<vector<char>> b;
string w;
};