212. Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.
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.

For example,
Given words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Return ["eat","oath"].

Note:
You may assume that all inputs are consist of lowercase letters a-z.

Solution:Backtrack + Trie

思路:
To optimize backtracking by stop backtracking earlier.
If the current candidate does not exist in all words' prefix, backtracking can be stopped immediately.
So: 先由words建Trie树,再dfs board,如果current candidate does not exist in all words' prefix, return
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    
    class TrieNode {
        public TrieNode[] children = new TrieNode[26];
        public boolean is_word;
    }
    
    private TrieNode buildTrie(String[] words) {
        TrieNode root = new TrieNode();
        for (String w: words) {
            TrieNode cur = root;
            for (int i = 0; i < w.length(); i++) {
                char c = w.charAt(i);
                if (cur.children[c - 'a'] == null) cur.children[c - 'a'] = new TrieNode();
                cur = cur.children[c - 'a'];
            }
            cur.is_word = true;
        }
        return root;
    }
    
    private void dfs(char[][] board, int y, int x, TrieNode node, boolean[][] used, StringBuilder cur_res, List<String> result) {
        if (y < 0 || x < 0 || y > board.length - 1 || x > board[0].length - 1) return;
        if(used[y][x]) return;
        if(node.children[board[y][x] - 'a'] == null) return; // essential trick
        
        used[y][x] = true;
        cur_res.append(board[y][x]);
        node = node.children[board[y][x] - 'a'];
        if(node.is_word) {
            result.add(cur_res.toString());
            node.is_word = false;  // de-duplicate
        }
        
        dfs(board, y, x - 1, node, used, cur_res, result); 
        dfs(board, y, x + 1, node, used, cur_res, result); 
        dfs(board, y - 1, x, node, used, cur_res, result); 
        dfs(board, y + 1, x, node, used, cur_res, result); 
        
        cur_res.deleteCharAt(cur_res.length() - 1);
        used[y][x] = false;
        
    }
    public List<String> findWords(char[][] board, String[] words) {
        List<String> result = new ArrayList<>();
        boolean[][] used = new boolean[board.length][board[0].length];
        
        TrieNode root = buildTrie(words);
        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board[0].length; x++) {
                dfs(board, y, x, root, used, new StringBuilder(), result);
            }
        }
        return result;
    }
    
    
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • 一問浮世繪哪般,名祿恩怨,淺笑盡了餘歡。二問深情諾幾許,癡狂迷戀,淚眼空了淒切。再問生死赴何時,浮沉糊塗,眉頭鎖了哀怨。
    沈进阅读 325评论 1 1
  • 新买了台服务器,随便倒腾,记录一下。 1. 安装 epel-release 1. 什么是epel 如果既想获得 R...
    zzpwestlife阅读 10,828评论 0 7
  • 写给年轻的女孩儿们: 你们一定也在经历着,选择什么学校,什么专业;选择和谁共度余生等等的人生中的各种选择题,先来看...
    冯大大在此阅读 691评论 0 0