Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
if(board == null || board.length == 0 || board[0] == null || board[0].length == 0)
return res;
if(words == null || words.length == 0)
return res;
for(String word: words) {
if(found(board, word))
if(!res.contains(word))
res.add(word);
}
return res;
}
public boolean found(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(board[i][j] == word.charAt(0)) {
if(helper(board, visited, i, j, 0, word))
return true;
}
}
}
return false;
}
public boolean helper(char[][] board, boolean[][] visited, int i, int j, int index, String word) {
int m = board.length;
int n = board[0].length;
if(index == word.length())
return true;
if(i >= m || i < 0 || j >= n || j < 0)
return false;
if(visited[i][j])
return false;
if(board[i][j] != word.charAt(index))
return false;
visited[i][j] = true;
if(helper(board, visited, i - 1, j, index + 1, word))
return true;
if(helper(board, visited, i + 1, j, index + 1, word))
return true;
if(helper(board, visited, i, j - 1, index + 1, word))
return true;
if(helper(board, visited, i, j + 1, index + 1, word))
return true;
visited[i][j] = false;
return false;
}
}