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