设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左,向右,向上,向下移动一格,如果一条路径经过了矩阵的某一格,那么该路径不再进入该格子。
class Solution
{
public:
bool pathExist(vector<vector<char>>& Graph,string word)
{
if(word.size()==0) return false;
for(int i=0;i!=Graph.size();i++)
{
for(int j=0;j!=Graph[0].size();j++)
{
if(helper(Graph,word,i,j,0)) return true;
}
}
return false;
}
bool helper(vector<vector<char>>& Graph,string word,int i,int j,int index)
{
if(index==word.size()) return true;
if(i<0 || i>Graph.size()-1 || j<0 || j>Graph[0].size()-1 || Graph[i][j]!=word[index]) return false;
Graph[i][j]+=26;//访问标记
bool isequal=helper(Graph,word,i-1,j,index+1) || helper(Graph,word,i+1,j,index+1) || helper(Graph,word,i,j-1,index+1) || helper(Graph,word,i,j+1,index+1);
Graph[i][j]-=26;//还原标记
return isequal;
}
};