DFS处理矩阵中的路径

设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左,向右,向上,向下移动一格,如果一条路径经过了矩阵的某一格,那么该路径不再进入该格子。

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;
  }
};

   
发布了22 篇原创文章 · 获赞 1 · 访问量 337

猜你喜欢

转载自blog.csdn.net/weixin_43086349/article/details/104689302