题目链接:牛客网
题目描述:
给出一个二维字符数组和一个单词,判断单词是否在数组中出现,
单词由相邻单元格的字母连接而成,相邻单元指的是上下左右相邻。同一单元格的字母不能多次使用。
例如:
给出的字符数组=
[↵ [“ABCE”],↵ [“SFCS”],↵ [“ADEE”]↵]
单词 =“ABCCED”, -> 返回 true,
单词 =“SEE”, ->返回 true,
单词 =“ABCB”, -> 返回 false.
解题思路:来自牛客网 nbgao
把每个点当成string的第一个点遍历,在递归函数中递归这个点的上下左右不超出board的位置找下一个匹配,直到找到所有word的匹配,返回true,否则返回false。
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
int m = board.size();
int n = board[0].size();
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(DST(board,i,j,0,word))
return true;
return false;
}
bool DST(vector<vector<char> > &board,int i,int j,int s,string word)
{
int m = board.size();
int n = board[0].size();
//符合word的这一位就继续往后找,不符合则直接返回false
if(word[s] == board[i][j])
{
//s == word.size()-1说明匹配完整个word.size
if(s == word.size()-1)
return true;
char c = board[i][j];
board[i][j] = '*';
//继续遍历上下左右寻找匹配的字符
bool flag = (i+1<m && DST(board,i+1,j,s+1,word)) ||
(i>0 && DST(board,i-1,j,s+1,word)) ||
(j+1<n && DST(board,i,j+1,s+1,word)) ||
(j>0 && DST(board,i,j-1,s+1,word));
board[i][j] = c;
return flag;
}
return false;
}
};