Recursive Search on 2D grid

65 Views Asked by At

I implemented this to solve a problem and it works but if I try a bigger board, say 100x100 then it gets super slow and eventually crashes. I am asking for an insight on how I can improve it to search faster. I am trying to find all the words on the board that match given a length N. The words to match need to be of min length N and to be in the lexicon. I’m not sure how to implement this in another way. I’ve tried different variations and they all seem slow. Any help would be appreciated. Thank you

public SortedSet<String> getWordsThatMatch(int minimumWordLength) {
  if (minimumWordLength < 1) {
     throw new IllegalArgumentException();
  }

  if (!lexiconLoaded) {
     throw new IllegalStateException();
  }

  SortedSet<String> result = new TreeSet<>();
  int n = board.length;

  for (int row = 0; row < n; row++) {
     for (int col = 0; col < n; col++) {
        StringBuilder currentWord = new StringBuilder();
        boolean[][] visited = new boolean[n][n];
        dfs(row, col, currentWord, visited, result, minimumWordLength);
     }
  }
  return result;
 }

 private void dfs(int row, int col, StringBuilder currentWord, boolean[][] visited,
                SortedSet<String> result, int minimumWordLength) {

  int n = board.length;

  if (row < 0 || col < 0 || row >= n || col >= n || visited[row][col]) {
     return;
  }

  if (currentWord.length() >= minimumWordLength && !isValidPrefix(currentWord.toString())) {
     return;
  }

  currentWord.append(board[row][col]);
  visited[row][col] = true;

  String word = currentWord.toString();

  if (word.length() >= minimumWordLength && isValidWord(word)) {
     result.add(word);
  }

  for (int dr = -1; dr <= 1; dr++) {
     for (int dc = -1; dc <= 1; dc++) {
        if (dr != 0 || dc != 0) {
           int newRow = row + dr;
           int newCol = col + dc;
           if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < n) {
              dfs(newRow, newCol, new StringBuilder(currentWord), visited, result, minimumWordLength);
           }
        }
     }
  }
  
  visited[row][col] = false;
  }
0

There are 0 best solutions below