|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import java.util.ArrayList;
|
| 4 | +import java.util.HashSet; |
4 | 5 | import java.util.List;
|
5 | 6 |
|
6 | 7 | public class _212 {
|
@@ -68,4 +69,43 @@ private TrieNode buildTrie(String[] words) {
|
68 | 69 | return root;
|
69 | 70 | }
|
70 | 71 | }
|
| 72 | + |
| 73 | + public static class Solution2 { |
| 74 | + public List<String> findWords (char[][] board, String[] words) { |
| 75 | + |
| 76 | + List<String> result = new ArrayList(); |
| 77 | + HashSet<String> set = new HashSet(); |
| 78 | + for (String word : words) { |
| 79 | + for (int i = 0; i < board.length; i++) { |
| 80 | + for (int j = 0; j < board[0].length; j++) { |
| 81 | + if (board[i][j] == word.charAt(0) && search(board, i, j, 0, word)) { |
| 82 | + set.add(word); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + result = new ArrayList<>(set); |
| 88 | + return result; |
| 89 | + } |
| 90 | + |
| 91 | + private boolean search(char[][] board, int i, int j, int count, String word) { |
| 92 | + if (count == word.length()) { |
| 93 | + return true; |
| 94 | + } |
| 95 | + |
| 96 | + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(count)) { |
| 97 | + return false; |
| 98 | + } |
| 99 | + |
| 100 | + char temp = board[i][j]; |
| 101 | + board[i][j] = ' '; |
| 102 | + |
| 103 | + boolean foundWord = search(board, i + 1, j, count + 1, word) |
| 104 | + || search(board, i - 1, j, count + 1, word) |
| 105 | + || search(board, i, j + 1, count + 1, word) |
| 106 | + || search(board, i, j - 1, count + 1, word); |
| 107 | + board[i][j] = temp; |
| 108 | + return foundWord; |
| 109 | + } |
| 110 | + } |
71 | 111 | }
|
0 commit comments