|
| 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; //Finding out no of rows and column in matrix |
| 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)) //comparing each element of matrix with first letter of word |
| 16 | + { |
| 17 | + if(dfs(board,i,j,word,0)) //applying dfs and checking if the word is present or not |
| 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()) //if position of word is equal to length of word that means word is present in array |
| 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]=='#') //checking the necessary condition to find out whether word exists or not |
| 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) || //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 |
| 41 | + |
| 42 | + board[i][j]=dup; //backtracking the string |
| 43 | + return ans; |
| 44 | + } |
| 45 | +} |
0 commit comments