Skip to content

Commit bfee961

Browse files
committed
Time: 319 ms (48.74%), Space: 10.6 MB (70.32%) - LeetHub
1 parent 13cdbe7 commit bfee961

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public:
3+
bool found=false;
4+
vector<pair<int,int>> dir={{1,0},{-1,0},{0,1},{0,-1}};
5+
bool isSafe(int i, int j, int n, int m, vector<vector<bool>> &vis){
6+
return i>=0 && j>=0 && i<n && j<m && !vis[i][j];
7+
}
8+
void solve(int i, int j, int n, int m, vector<vector<bool>> &vis, vector<vector<char>>& board, string &word, int ind){
9+
if(found){
10+
return;
11+
}
12+
if (board[i][j] != word[ind]) return;
13+
if(!isSafe(i,j,n,m,vis)){
14+
return;
15+
}
16+
if (ind == word.size() - 1) { // last char matched
17+
found = true;
18+
return;
19+
}
20+
// cout<<"1 call"<<endl;
21+
vis[i][j]=true;
22+
for(int k=0;k<4;k++){
23+
// cout<<"2 call"<<endl;
24+
int newI=i+dir[k].first;
25+
int newJ=j+dir[k].second;
26+
if(isSafe(newI,newJ,n,m,vis)){
27+
solve(newI,newJ,n,m,vis,board,word,ind+1);
28+
}
29+
}
30+
vis[i][j]=false;
31+
}
32+
bool exist(vector<vector<char>>& board, string word) {
33+
int n=board.size(),m=board[0].size();
34+
int i=0,j=0,ind=0;
35+
vector<vector<bool>> vis(n,vector<bool>(m,false));
36+
for (int i = 0; i < n; i++) {
37+
for (int j = 0; j < m; j++) {
38+
solve(i, j, n, m, vis, board, word, 0);
39+
if (found) return true;
40+
}
41+
}
42+
return false;
43+
}
44+
};

0 commit comments

Comments
 (0)