Advertisement
i4640

LC212_BADSOL

Aug 8th, 2018
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. // LC 212 FAILED SOLUTION (34/37)
  2. // https://leetcode.com/problems/word-search-ii/description/
  3.  
  4. class Solution {
  5. public List<String> findWords(char[][] board, String[] words) {
  6. List<String> ans = new ArrayList<String>();
  7. if (board.length == 0 || board[0].length == 0) {
  8. return ans;
  9. }
  10. for (int i = 0; i < board.length; i++) {
  11. for (int j = 0; j < board[0].length; j++) {
  12. for (String w : words) {
  13. if (board[i][j] == w.charAt(0) &&
  14. BT(board, new int[] {i, j}, w, new boolean[board.length][board[0].length]) &&
  15. !ans.contains(w)) {
  16. ans.add (w);
  17. }
  18. }
  19. }
  20. }
  21. return ans;
  22. }
  23. public boolean BT(char[][] board, int[] pos, String word, boolean[][] visited) {
  24. if (board[pos[0]][pos[1]] != word.charAt(0)) {
  25. return false;
  26. }
  27. else if (word.length() == 1) {
  28. return true;
  29. }
  30. visited[pos[0]][pos[1]] = true;
  31. int[][] dirs = new int[][] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
  32. for (int[] dir : dirs) {
  33. int x = dir[0] + pos[0];
  34. int y = dir[1] + pos[1];
  35. if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && !visited[x][y]) {
  36. if (BT(board, new int[] {x, y}, word.substring(1), visited)) {
  37. return true;
  38. }
  39. }
  40. }
  41. return false;
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement