3

I am working a word search problem. I correctly implemented dfs search but there is trival error somewhere else.

For the word in this list ["oath","pea","eat","rain"], "oath" and "eat" can be found in the board:

[ 
 ['o','a','a','n'],
 ['e','t','a','e'],
 ['i','h','k','r'],
 ['i','f','l','v']
                  ]

I designed a program to search all the words in a given board. Here is my code using dfs:

public class WordSearchII {
public List<String> findWords(char[][] board, String[] words) {

    List<String> res = new ArrayList<String>();

    // in order to reinitailize the board every time after 
    //I search each word in the board
    char[][] temp = new char[board.length][board[0].length];
    for (int i=0; i<board.length; i++){
            for(int j=0; j<board[i].length; j++){
                temp[i][j]=board[i][j];
            }
        }

    for (String word : words){
        board=temp; //reintialize the board
        for (int i=0; i<board.length; i++){
            for(int j=0; j<board[i].length; j++){
                if (find_word(board, word, i, j, 0))// bfs search
                res.add(word);
            }
        }
    }
    return res;
}

public boolean find_word(char[][] board, String word, int i, int j, int index){

    if (index==word.length()) return true;

    if (i<0 || i>=board.length || j<0 || j>=board[i].length) return false;

    if (board[i][j]!=word.charAt(index)) return false;

    char temp=board[i][j];

    board[i][j] = '*';

    if (find_word(board, word, i-1, j, index++)||
        find_word(board, word, i+1, j, index++)||
        find_word(board, word, i, j-1, index++)||
        find_word(board, word, i, j+1, index++)) return true;

    board[i][j]= temp;

    return false;

}
}

For the given example above, my code returned [eat, eat] weirdly.

Since I iterate through the list of words and judge on by one if they can be found in the board. Even though I failed to find 'oath', 'eat' should not be added twice into the result list.

DMH
  • 3,875
  • 2
  • 26
  • 25
Dengke Liu
  • 131
  • 1
  • 1
  • 10

1 Answers1

2

This seems to be the problem:

if (find_word(board, word, i-1, j, index++)||
    find_word(board, word, i+1, j, index++)||
    find_word(board, word, i, j-1, index++)||
    find_word(board, word, i, j+1, index++)) return true;

You're incrementing the index every time but you've to pass index + 1 to every sub call.

if (find_word(board, word, i-1, j, index+1)||
    find_word(board, word, i+1, j, index+1)||
    find_word(board, word, i, j-1, index+1)||
    find_word(board, word, i, j+1, index+1)) return true;
Flown
  • 11,480
  • 3
  • 45
  • 62