|
|
我也写一个trie+dfs的穷举
- public class Solution {
- public String longest = "";
- public static void main(String[] args) {
- String[] dict = {"abcddd","abc"};
- char[][] mat = {{'a','b','c'},{'d','d','d'},{'b','b','d'}};
- Solution sol = new Solution();
- sol.findmaxPath(dict, mat);
- System.out.println(sol.longest);
- String[] dict2 = {"abs","abc","dd","bb"};
- sol = new Solution();
- sol.findmaxPath(dict2, mat);
- System.out.println(sol.longest);
- }
- public void findmaxPath(String[] dict, char[][] mat) {
- Trie trie = new Trie();
- for (String s : dict) {
- trie.insert(s);
- }
- int rows = mat.length;
- int cols = mat[0].length;
- boolean[][] taken = new boolean[rows][cols];
- for (int row = 0; row < rows; row++) {
- for (int col = 0; col < cols; col++) {
- recursiveHelper(trie, mat, row, col, taken, "", "");
- }
- }
- }
- private void recursiveHelper(Trie trie, char[][] mat, int row, int col, boolean[][] taken, String prev, String current) {
- int rows = mat.length;
- int cols = mat[0].length;
- if (row < 0 || col < 0 || row >= rows || col >= cols || taken[row][col]) {
- return;
- }
- char ch = mat[row][col];
- taken[row][col] = true;
- current += ch;
- // Case 1 : use 'current' as the end of the prefix
- if (trie.search(current)) {
- if ((prev + current).length() > this.longest.length()) {
- this.longest = prev + current;
- }
- recursiveHelper(trie, mat, row + 1, col, taken, prev + current, "");
- recursiveHelper(trie, mat, row - 1, col, taken, prev + current, "");
- recursiveHelper(trie, mat, row, col + 1, taken, prev + current, "");
- recursiveHelper(trie, mat, row, col - 1, taken, prev + current, "");
- }
- // Case 2 : use 'current' as the start of the suffix
- // e.g. we should match 'abcddd' instead of 'abc' in dict
- if (trie.startsWith(current)) {
- recursiveHelper(trie, mat, row + 1, col, taken, prev, current);
- recursiveHelper(trie, mat, row - 1, col, taken, prev, current);
- recursiveHelper(trie, mat, row, col + 1, taken, prev, current);
- recursiveHelper(trie, mat, row, col - 1, taken, prev, current);
- }
- taken[row][col] = false;
- }
- }
复制代码 |
|