Skip to content

Commit 705e675

Browse files
committed
Time: 614 ms (59.14%), Space: 8.4 MB (5.54%) - LeetHub
1 parent ae86db7 commit 705e675

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

0079-word-search/0079-word-search.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
int dx[4]={0,0,1,-1};
4+
int dy[4]={1,-1,0,0};
5+
bool dfs(int i, int j, int count, vector<vector<char>>& board, string word, int n, int m){
6+
7+
if(count == word.size() ) return true;
8+
if(i < 0 || j < 0 || i >= n || j >= m) return false;
9+
if(word[count] != board[i][j]) return false;
10+
11+
char temp = board[i][j];
12+
board[i][j] = ' ';
13+
14+
bool ans = dfs(i-1,j,count+1,board,word,n,m) ||
15+
dfs(i+1,j,count+1,board,word,n,m) ||
16+
dfs(i,j-1,count+1,board,word,n,m) ||
17+
dfs(i,j+1,count+1,board,word,n,m);
18+
19+
board[i][j] = temp; // make board as it is for the upcoming calls
20+
return ans;
21+
22+
}
23+
24+
bool exist(vector<vector<char>>& board, string word) {
25+
int n = board.size();
26+
int m = board[0].size();
27+
28+
for(int i = 0 ; i < n ; i++){
29+
for(int j = 0 ; j < m ; j++){
30+
vector<vector<bool>>vis(n,vector<bool>(m,false));
31+
if(board[i][j] == word[0] && dfs(i,j,0,board,word,n,m) == true) return true;
32+
}
33+
}
34+
return false;
35+
36+
}
37+
};

0 commit comments

Comments
 (0)