212. Word SearchII

題目:
Given a 2D board and a list of words from the dictionary, find all words in the board.java

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.ui

For example,
Given words = ["oath","pea","eat","rain"] and board =code

[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].it

解答:
這題我原來是在word search I的基礎上,用backtracking來作的,代碼以下:io

public boolean exist(char[][] board, String word, int i, int j, int pos, boolean[][] visited) {
    if (pos == word.length()) return true;
    if (i < 0 || i > board.length - 1 || j < 0 || j > board[i].length - 1) return false;
    if (visited[i][j] || board[i][j] != word.charAt(pos)) return false;
    
    visited[i][j] = true;
    int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (int k = 0; k < dir.length; k++) {
        int x = i + dir[k][0], y = j + dir[k][1];
        if (exist(board, word, x, y, pos + 1, visited)) {
            return true;
        }
    }
    visited[i][j] = false;
    return false;
}

public boolean helper(char[][] board, String word) {
    boolean[][] visited = new boolean[board.length][board[0].length];
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            if (exist(board, word, i, j, 0, visited)) {
                return true;
            }
        }
    }
    return false;
}

public List<String> findWords(char[][] board, String[] words) {
    List<String> result = new ArrayList<String>();
    if (board == null || board.length == 0 || board[0].length == 0) return result;
 
    for (String word : words) {
        if (helper(board, word)) {
            if (!result.contains(word)) {
                result.add(word);
            }
        }
    }
    
    return result;
}

作完以後,結果運行是對的,可是TLE了,因此確定是有更好的辦法。在TLE的test case裏,我看到是當prefix相同時,若是用backtracking那麼會不斷地掃同一個位置的prefix,很是的冗餘,那麼怎麼把prefix提取出來只掃一次呢?一個很好的辦法就是反過來,用trie樹先把單詞存起來,而後掃board,掃board的時候用trie樹中的可能出現的單詞做爲限制條件,那麼當掃到一個trie中結尾存在的單詞時,把它存進result中去。代碼以下:class

class TrieNode {
    TrieNode[] next = new TrieNode[26];
    String word;
}

public TrieNode buildTrie(String[] words) {
    TrieNode root = new TrieNode();
    for (String word : words) {
        TrieNode p = root;
        for (char c : word.toCharArray()) {
            int i = c - 'a';
            if (p.next[i] == null) p.next[i] = new TrieNode();
            p = p.next[i];
        }
        p.word = word;
    }
    return root;
}

public void dfs(List<String> result, char[][] board, TrieNode p, int i, int j) {
    char c = board[i][j];
    if (c == '#' || p.next[c - 'a'] == null) return;
    p = p.next[c - 'a'];
    
    if (p.word != null) {
        result.add(p.word);
        p.word = null; //去重
    }
    
    board[i][j] = '#';
    int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (int k = 0; k < dir.length; k++) {
        int x = i + dir[k][0], y = j + dir[k][1];
        if (x < 0 || x > board.length - 1 || y < 0 || y > board[i].length - 1) continue;
        dfs(result, board, p, x, y);
    }
    board[i][j] = c;
}

public List<String> findWords(char[][] board, String[] words) {
    List<String> result = new ArrayList<String>();
    if (board == null || board.length == 0 || board[0].length == 0) return result;
    
    TrieNode root = buildTrie(words);
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            dfs(result, board, root, i, j);
        }
    }
    return result;
}
相關文章
相關標籤/搜索