• Source
    1. import java.util.*;
    2. import java.lang.*;
    3. import java.io.*;
    4.  
    5. class Ideone
    6. {
    7. public static void main(String[] args){
    8. char[][] charGrid = {
    9. {'V', 'I', 'J', 'A', 'R'},
    10. {'E', 'V', 'P', 'V', 'D'},
    11. {'J', 'I', 'J', 'A', 'R'},
    12. {'A', 'V', 'I', 'K', 'H'},
    13. {'R', 'T', 'J', 'A', 'R'}
    14. };
    15. String target= "RAJIV";
    16. boolean[][] solution = new boolean[charGrid.length][charGrid[0].length];
    17.  
    18. //Construct traversal directions( 4 directions --> left, right, up, down)
    19. int[] xPos = {0, 0, 1, -1};
    20. int[] yPos = {1, -1, 0, 0};
    21.  
    22. for(int i=0; i<charGrid.length; i++){
    23. for(int j=0; j<charGrid[0].length; j++){
    24. boolean wordExists = checkWordExistance(charGrid, solution, i, j, xPos, yPos, 0, target);
    25. if(wordExists){
    26. printPath(solution, charGrid);
    27. resetTraversalMatrix(solution);
    28. }
    29. }
    30. }
    31. }
    32.  
    33. private static void resetTraversalMatrix(boolean[][] solution){
    34. for(int i=0; i<solution.length; i++){
    35. for(int j=0; j<solution[0].length; j++){
    36. solution[i][j] = false;
    37. }
    38. }
    39. }
    40.  
    41. private static void printPath(boolean[][] solution, char[][] charGrid){
    42. System.out.println("\n\n");
    43. for(int i=0; i<charGrid.length; i++){
    44. for(int j=0; j< charGrid[0].length; j++){
    45. char ch = solution[i][j] ? charGrid[i][j] : ' ';
    46. System.out.print(" "+ ch + " ");
    47. }
    48. System.out.println();
    49. }
    50. }
    51.  
    52. private static boolean checkWordExistance(char[][] charGrid, boolean[][] solution, int curX, int curY, int[] xPos, int[] yPos, int targetTracker, String target){
    53.  
    54. if(target == null || target.length() == 0) return true;
    55.  
    56. if(targetTracker == target.length()) return true;
    57.  
    58. for(int k=0; k<xPos.length; k++){
    59. int nextXPos = curX + xPos[k];
    60. int nextYPos = curY + yPos[k];
    61.  
    62. if(target.charAt(targetTracker) == charGrid[curX][curY] && isSafeMove(solution, nextXPos, nextYPos)){
    63. solution[curX][curY] = true;
    64. if(checkWordExistance(charGrid, solution, nextXPos, nextYPos, xPos, yPos, targetTracker+1, target)){
    65. return true;
    66. }else{
    67. solution[curX][curY] = false;
    68. }
    69. }else{
    70. solution[curX][curY] = false;
    71. }
    72. }
    73. return false;
    74. }
    75.  
    76. private static boolean isSafeMove(boolean[][] solution, int curX, int curY){
    77. if(curX >= 0 && curX < solution.length && curY >= 0 && curY < solution[0].length && !solution[curX][curY]){
    78. return true;
    79. } else{
    80. return false;
    81. }
    82. }
    83. }
    84.