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.

click to show hint.

Show Tags
Show Similar Problems

Have you met this question in a real interview?

silu : Same to Word Search I , we using DFS to search, but it will cost to much time. We use Trie tree to storage the string words which we want to seach. We can cut off some impossible path.

public class Solution {
    public class TrieNode {
        boolean isEnd;
        TrieNode[] child;
        public TrieNode() { // constructor
            this.isEnd = false;
            this.child = new TrieNode[26];
        }
    }
    public class Trie {
        TrieNode root;
        public Trie() { // constructor
            this.root = new TrieNode();
        }
        public void insert(String word) {
            TrieNode runner = root;
            char[] str = word.toCharArray();
            for(char c : str) {
                if (runner.child[c-'a'] == null) {
                    runner.child[c-'a'] = new TrieNode();
                }
                runner = runner.child[c-'a'];
            }
            runner.isEnd = true;
        }
        public boolean search(String word) {
            TrieNode runner = root;
            char[] str = word.toCharArray();
            for(char c : str) {
                if (runner.child[c-'a'] == null) return false;
                runner = runner.child[c-'a'];
            }
            if (runner.isEnd == false) return false;
            return true;
        }
        public boolean startWith(String prefix) {
            TrieNode runner = root;
            char[] str = prefix.toCharArray();
            for(char c : str) {
                if (runner.child[c-'a'] == null) return false;
                runner=runner.child[c-'a'];
            }
            return true;
        }
    }

    public List<String> findWords(char[][] board, String[] words) {
        List<String> result = new ArrayList<String>();
        if (words.length == 0 || board.length == 0 || board[0].length == 0) return result;

        int row = board.length;
        int column = board[0].length;

        Trie dict = new Trie();

        for(String str : words) dict.insert(str); // insert all the words into Trie
        boolean[][] visited = new boolean[row][column];
        StringBuilder sb = new StringBuilder();
        Set<String> res = new HashSet<String>();
        for(int i=0; i<row; i++) { // try start with every single character
            for(int j=0; j<column; j++) {
                findWordsHelper(board, visited, i, j, dict, sb, res);
            }
        }
        for(String s : res) result.add(s);
        return result;
    }

    public void findWordsHelper (char[][] board, boolean[][] visited, int x, int y, Trie dict, StringBuilder sb, Set<String> res) {
        int row = board.length;
        int column = board[0].length;
        if (x<0 || x>=row || y<0 || y>=column) return;
        if (visited[x][y] == true) return;

        String str = sb.append(board[x][y]).toString();
        if (!dict.startWith(str)) { // check if dict has a starWith for current str
            sb.deleteCharAt(sb.length()-1); // delete the character
            return;
        }
        if (dict.search(str)) res.add(str); // if dict HAS a starWith for strm check if str is a word & add to res
        // keep going as dict has a starWith for current str
        visited[x][y] = true;
        findWordsHelper(board, visited, x+1, y, dict, sb, res);
        findWordsHelper(board, visited, x, y+1, dict, sb, res);
        findWordsHelper(board, visited, x-1, y, dict, sb, res);
        findWordsHelper(board, visited, x, y-1, dict, sb, res);
        visited[x][y] = false;
        sb.deleteCharAt(sb.length()-1); // backtracking, delete the character
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章