LeetCode--212--hard--WordSearchII

  summary:

  dfs traversal | backtrack | trie pruning

package com.odyssey.app.algorithm.lc.trie;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Dingsheng Huang
 * @date 2020/3/13 14:38
 *
 * 212
 * hard
 * https://leetcode.com/problems/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.
 *
 *
 *
 * Example:
 *
 * Input:
 * board = [
 *   ['o','a','a','n'],
 *   ['e','t','a','e'],
 *   ['i','h','k','r'],
 *   ['i','f','l','v']
 * ]
 * words = ["oath","pea","eat","rain"]
 *
 * Output: ["eat","oath"]
 *
 *
 * Note:
 *
 * All inputs are consist of lowercase letters a-z.
 * The values of words are distinct.
 *
 */
public class WordSearchII {


    Set<String> result = new HashSet<>();
    public List<String> findWords(char[][] board, String[] words) {
        TrieNode root = new TrieNode();
        for (String word :words) {
            root.insert(root, word);
        }
        /**
         * [["a","a"]]
         * ["a"]
         */
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j <board[i].length; j++) {
                traversal(board, i, j, root);
            }
        }
        List<String> res = new ArrayList<>();
        res.addAll(result);
        return res;
    }

    private void traversal(char[][] board, int x, int y, TrieNode trie) {
        // access the border
        if (x < 0 ||  y < 0 || x > board.length - 1 || y > board[x].length - 1  || board[x][y] == '1') {
            return;
        }
        // pruning
        if (trie.children[board[x][y] - 'a'] == null) {
            return;
        }
        if (trie.children[board[x][y] - 'a'].word.length() > 0) {
            result.add(trie.children[board[x][y] - 'a'].word);
        }
        char temp = board[x][y];
        board[x][y] = '1';
        traversal(board, x - 1, y, trie.children[temp - 'a']);
        traversal(board, x + 1, y, trie.children[temp - 'a']);
        traversal(board, x, y - 1, trie.children[temp - 'a']);
        traversal(board, x, y + 1, trie.children[temp - 'a']);
        // backtrack
        board[x][y] = temp;

    }

    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        String word = "";

        void insert(TrieNode root, String word) {
            TrieNode currNode = root;
            char[] chs = word.toCharArray();
            for (int i = 0; i < chs.length; i++) {
                int idx = chs[i] - 'a';
                if (currNode.children[idx] == null) {
                    currNode.children[idx] = new TrieNode();
                }
                currNode = currNode.children[idx];
            }
            currNode.word = word;
        }
    }
}
发布了205 篇原创文章 · 获赞 27 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/104842239
212
今日推荐