I have to write a program for a Boggle-like game, and I currently have it check each letter below the current one to see if they make a word. So for a board like so:
W O Y R
F U M F
H T R V
I G S W
The only word it would find is "OUT" going from top to bottom. When it finds part of a word it puts that letter into a string and sets it to null so it won't use a letter twice in the same word (the full algorithm has to be able to search in multiple directions). I use a stack to keep track of the coordinates of the letters I've used so I can backtrack, and every time I pop the stack I take the last letter of the string and put it back into the board in its original position. But the issue is that if multiple letters are removed, it places them all in the same index, overwriting the previous one. So in the case of "OUT" the board ends up looking like this after replacing the three letters:
W null Y R
F null M F
H O R V
I G S W
I've gone through my code and tried rewriting it twice but it always does this. Do you have any insight as to why this is happening?
private void checkNeighbors(LetterCoor center){
String check = out;
while (!path.empty()){
if(center.getDirec()==0){//If the direction to check is down
System.out.println("Bottom");
if((center.getRow())+1<sideLength && board[(center.getRow())+1][center.getCol()]!=null){//makes sure the space below is !null and !out of bounds
check+=board[center.getRow()+1][center.getCol()];
System.out.println("Checking " + check);
if(isValidWord(check)){//checks if string is part of the lexicon
center.nextNeighbor();
board[center.getRow()+1][center.getCol()]=null;
center = new LetterCoor(center.getRow()+1, center.getCol(), 0);
System.out.println("push " + check.substring(check.length()-1));
path.push(center);
out=check;
}
else{
center=(LetterCoor) path.pop();
center.nextNeighbor();
path.push(center);
}
}//end of null if
else{
System.out.println("Null or end of board");
center=(LetterCoor) path.pop();
center.nextNeighbor();
path.push(center);
}
}//end of direc 0 if
else{
System.out.println("pop " + out.substring(out.length()-1,out.length()));
center=(LetterCoor) path.pop();
center.nextNeighbor();
board[center.getRow()][center.getCol()]=out.substring(out.length()-1,out.length());
out=out.substring(0,out.length()-1);
if (center.getDirec()<1){
path.push(center);
}
}
System.out.println("Current string is " + out);
}//end of while loop
}
If you need any clarification of my code please let me know.
Also, as clarification the LeterCoor object stores three ints. The first is the row index of the letter, the second is the column index and the third indicates which direction it is searching in (0=down, 1=down right, 2=right, etc)