Sanath12345

Untitled

Jun 28th, 2023
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. class Solution {
  2. public:
  3. bool help(int i,int j,int k,vector<vector<char>>& b,string &w,vector<vector<int>> &vis){
  4. if(k==w.length()){
  5. return true;
  6. }
  7. if(i==int(b.size()) || j==int(b[0].size()) || i<0 || j<0 || vis[i][j]==1) return false;
  8. if(b[i][j]!=w[k]) return false;
  9. vis[i][j]=1;
  10. bool opt1=help(i+1,j,k+(w[k]==b[i][j]),b,w,vis);
  11. bool opt2=help(i-1,j,k+(w[k]==b[i][j]),b,w,vis);
  12. bool opt3=help(i,j+1,k+(w[k]==b[i][j]),b,w,vis);
  13. bool opt4=help(i,j-1,k+(w[k]==b[i][j]),b,w,vis);
  14. vis[i][j]=0;
  15. return (opt1 || opt2 || opt3 || opt4);
  16. }
  17. bool exist(vector<vector<char>>& b, string w) {
  18. int n=b.size(),m=b[0].size();
  19. vector<vector<int>> vis(n,vector<int>(m,0));
  20. for(int i=0;i<n;i++){
  21. for(int j=0;j<m;j++){
  22. if(help(i,j,0,b,w,vis)) return true;
  23. }
  24. }
  25. return false;
  26. }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment