1import java.util.ArrayList;2import java.util.List;3
4class Solution {5 private char[][] board;6 private int rows;7 private int cols;8
9 public List<String> findWords(char[][] board, String[] words) {10 this.board = board;11 this.rows = board.length;12 this.cols = board[0].length;13 List<String> res = new ArrayList<>();14 for (String word : words) {15 if (exists(word)) {16 res.add(word);17 }18 }19 return res;20 }21
22 private boolean exists(String word) {23 for (int r = 0; r < rows; r++) {24 for (int c = 0; c < cols; c++) {25 if (dfs(r, c, word, 0)) {26 return true;27 }28 }29 }30 return false;31 }32
33 private boolean dfs(int r, int c, String word, int i) {34 35 if (i == word.length()) {36 return true;37 }38 if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word.charAt(i)) {39 return false;40 }41 char saved = board[r][c];42 43 board[r][c] = '#';44 boolean found = dfs(r + 1, c, word, i + 1) || dfs(r - 1, c, word, i + 1)45 || dfs(r, c + 1, word, i + 1) || dfs(r, c - 1, word, i + 1);46 47 board[r][c] = saved;48 return found;49 }50}