Word Search II

51 篇文章 0 订阅
35 篇文章 0 订阅

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
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值