Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- bool help(int i,int j,int k,vector<vector<char>>& b,string &w,vector<vector<int>> &vis){
- if(k==w.length()){
- return true;
- }
- if(i==int(b.size()) || j==int(b[0].size()) || i<0 || j<0 || vis[i][j]==1) return false;
- if(b[i][j]!=w[k]) return false;
- vis[i][j]=1;
- bool opt1=help(i+1,j,k+(w[k]==b[i][j]),b,w,vis);
- bool opt2=help(i-1,j,k+(w[k]==b[i][j]),b,w,vis);
- bool opt3=help(i,j+1,k+(w[k]==b[i][j]),b,w,vis);
- bool opt4=help(i,j-1,k+(w[k]==b[i][j]),b,w,vis);
- vis[i][j]=0;
- return (opt1 || opt2 || opt3 || opt4);
- }
- bool exist(vector<vector<char>>& b, string w) {
- int n=b.size(),m=b[0].size();
- vector<vector<int>> vis(n,vector<int>(m,0));
- for(int i=0;i<n;i++){
- for(int j=0;j<m;j++){
- if(help(i,j,0,b,w,vis)) return true;
- }
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment