212. Word Search II

来源:互联网 发布:烟草网络学校考试答案 编辑:程序博客网 时间:2024/05/19 14:55

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.

public class Solution {    class TrieNode {        TrieNode[] next = new TrieNode[26];        String word;    }    public List<String> findWords(char[][] board, String[] words) {        List<String> result = new ArrayList<String>();        TrieNode root = buildTrie(words);        for(int i = 0; i < board.length; i++) {            for(int j = 0; j < board[i].length; j++) {                dfs(board, i, j, root, result);            }        }        return result;    }    public TrieNode buildTrie(String[] words) {        TrieNode root = new TrieNode();        for (int i = 0; i < words.length; i++) {            String word = words[i];            TrieNode pnode = root;            for (char c : word.toCharArray()) {                if(pnode.next[c-'a'] == null) pnode.next[c-'a'] = new TrieNode();                pnode = pnode.next[c-'a'];            }            pnode.word = word;        }        return root;    }    public void dfs(char[][] board, int i, int j, TrieNode root, List<String> res) {        char c = board[i][j];        if(c == '#' || root.next[c-'a'] == null) return;        root = root.next[c-'a'];        if(root.word != null) {            res.add(root.word);            root.word = null;        }        board[i][j] = '#';        if(i > 0) dfs(board, i-1, j, root, res);        if(j > 0) dfs(board, i, j-1, root, res);        if(i < board.length-1) dfs(board, i+1, j, root, res);        if(j < board[0].length-1) dfs(board, i, j+1, root, res);        board[i][j] = c;    }}
0 0
原创粉丝点击