1+ /*Given an m x n grid of characters board and a string word, return true if word exists in the grid.
2+ The word can be constructed from letters of sequentially adjacent cells,
3+ where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
4+ */
5+
6+ class Solution {
7+ public boolean exist (char [][] board , String word ) {
8+
9+ int M =board .length , N =board [0 ].length ;
10+
11+ for (int i =0 ;i <M ;i ++)
12+ {
13+ for (int j =0 ;j <N ;j ++)
14+ {
15+ if (board [i ][j ]==word .charAt (0 ))
16+ {
17+ if (dfs (board ,i ,j ,word ,0 )) //applying dfs
18+ return true ;
19+ }
20+ }
21+ }
22+ return false ;
23+ }
24+
25+ public boolean dfs (char [][] board ,int i ,int j ,String word ,int pos )
26+ {
27+ if (pos ==word .length ())
28+ return true ;
29+
30+ int M =board .length , N =board [0 ].length ;
31+ if (i < 0 || i >= M || j < 0 || j >= N || board [i ][j ]!=word .charAt (pos ) || board [i ][j ]=='#' ) //comparing the required conditions
32+ return false ;
33+
34+ char dup =board [i ][j ];
35+ board [i ][j ]='#' ;
36+
37+ boolean ans = dfs (board , i + 1 , j , word , pos + 1 ) ||
38+ dfs (board , i - 1 , j , word , pos + 1 ) ||
39+ dfs (board , i , j + 1 , word , pos + 1 ) ||
40+ dfs (board , i , j - 1 , word , pos + 1 );
41+
42+ board [i ][j ]=dup ; //backtracking the string
43+ return ans ;
44+ }
45+ }
0 commit comments