Skip to content

Commit 7fbdb88

Browse files
authored
Update wordCount.java
1 parent 810be43 commit 7fbdb88

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

LeetCode/wordCount.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66
class Solution {
77
public boolean exist(char[][] board, String word) {
88

9-
int M=board.length, N=board[0].length;
9+
int M=board.length, N=board[0].length; //Finding out no of rows and column in matrix
1010

1111
for(int i=0;i<M;i++)
1212
{
1313
for(int j=0;j<N;j++)
1414
{
15-
if(board[i][j]==word.charAt(0))
15+
if(board[i][j]==word.charAt(0)) //comparing each element of matrix with first letter of word
1616
{
17-
if(dfs(board,i,j,word,0)) //applying dfs
17+
if(dfs(board,i,j,word,0)) //applying dfs and checking if the word is present or not
1818
return true;
1919
}
2020
}
@@ -24,22 +24,22 @@ public boolean exist(char[][] board, String word) {
2424

2525
public boolean dfs(char[][] board,int i,int j,String word,int pos)
2626
{
27-
if(pos==word.length())
27+
if(pos==word.length()) //if position of word is equal to length of word that means word is present in array
2828
return true;
2929

3030
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
31+
if(i < 0 || i >= M || j < 0 || j >= N || board[i][j]!=word.charAt(pos) || board[i][j]=='#') //checking the necessary condition to find out whether word exists or not
3232
return false;
3333

3434
char dup=board[i][j];
3535
board[i][j]='#';
3636

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);
37+
boolean ans = dfs(board, i + 1, j, word, pos + 1) || //traversing one letter right
38+
dfs(board, i - 1, j, word, pos + 1) || ////traversing one letter left
39+
dfs(board, i, j + 1, word, pos + 1) || //traversing one letter up
40+
dfs(board, i, j - 1, word, pos + 1); ////traversing one letter down
4141

4242
board[i][j]=dup; //backtracking the string
4343
return ans;
4444
}
45-
}
45+
}

0 commit comments

Comments
 (0)