|
| 1 | +//This is a typical backtracking problem similar to Number of Islands. |
| 2 | +//In number of Isalnds, we sinked the islands. Here, we will do the same by adding changing the value of the char. |
| 3 | +//I added 100 because it will exceed the ascii limit for characters and will change it to some ascii value which is not an alphabet. |
| 4 | + |
| 5 | +classSolution { |
| 6 | +publicbooleanexist(char[][]board,Stringword) { |
| 7 | +intm =board.length; |
| 8 | +intn =board[0].length; |
| 9 | +for (inti =0;i<m;i++) { |
| 10 | +for (intj =0;j<n;j++) { |
| 11 | +if (check(board,word,i,j,m,n,0)) { |
| 12 | +returntrue; |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | +returnfalse; |
| 17 | + } |
| 18 | + |
| 19 | +publicbooleancheck(char[][]board,Stringword,inti,intj,intm,intn,intcur) { |
| 20 | +if (cur>=word.length()) |
| 21 | +returntrue; |
| 22 | +if (i<0 ||j<0 ||i>=m ||j>=n ||board[i][j]!=word.charAt(cur)) |
| 23 | +returnfalse; |
| 24 | +booleanexist =false; |
| 25 | +if (board[i][j]==word.charAt(cur)) { |
| 26 | +board[i][j] +=100; |
| 27 | +exist =check(board,word,i+1,j,m,n,cur+1) || |
| 28 | +check(board,word,i,j+1,m,n,cur+1) || |
| 29 | +check(board,word,i-1,j,m,n,cur+1) || |
| 30 | +check(board,word,i,j-1,m,n,cur+1); |
| 31 | +board[i][j] -=100; |
| 32 | + } |
| 33 | +returnexist; |
| 34 | + } |
| 35 | +} |