import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main
(String[] args
){ char[][] charGrid = {
{'V', 'I', 'J', 'A', 'R'},
{'E', 'V', 'P', 'V', 'D'},
{'J', 'I', 'J', 'A', 'R'},
{'A', 'V', 'I', 'K', 'H'},
{'R', 'T', 'J', 'A', 'R'}
};
boolean[][] solution = new boolean[charGrid.length][charGrid[0].length];
//Construct traversal directions( 4 directions --> left, right, up, down)
int[] xPos = {0, 0, 1, -1};
int[] yPos = {1, -1, 0, 0};
for(int i=0; i<charGrid.length; i++){
for(int j=0; j<charGrid[0].length; j++){
boolean wordExists = checkWordExistance(charGrid, solution, i, j, xPos, yPos, 0, target);
if(wordExists){
printPath(solution, charGrid);
resetTraversalMatrix(solution);
}
}
}
}
private static void resetTraversalMatrix(boolean[][] solution){
for(int i=0; i<solution.length; i++){
for(int j=0; j<solution[0].length; j++){
solution[i][j] = false;
}
}
}
private static void printPath(boolean[][] solution, char[][] charGrid){
for(int i=0; i<charGrid.length; i++){
for(int j=0; j< charGrid[0].length; j++){
char ch = solution[i][j] ? charGrid[i][j] : ' ';
System.
out.
print(" "+ ch
+ " "); }
}
}
private static boolean checkWordExistance
(char[][] charGrid,
boolean[][] solution,
int curX,
int curY,
int[] xPos,
int[] yPos,
int targetTracker,
String target
){
if(target == null || target.length() == 0) return true;
if(targetTracker == target.length()) return true;
for(int k=0; k<xPos.length; k++){
int nextXPos = curX + xPos[k];
int nextYPos = curY + yPos[k];
if(target.charAt(targetTracker) == charGrid[curX][curY] && isSafeMove(solution, nextXPos, nextYPos)){
solution[curX][curY] = true;
if(checkWordExistance(charGrid, solution, nextXPos, nextYPos, xPos, yPos, targetTracker+1, target)){
return true;
}else{
solution[curX][curY] = false;
}
}else{
solution[curX][curY] = false;
}
}
return false;
}
private static boolean isSafeMove(boolean[][] solution, int curX, int curY){
if(curX >= 0 && curX < solution.length && curY >= 0 && curY < solution[0].length && !solution[curX][curY]){
return true;
} else{
return false;
}
}
}