zoukankan      html  css  js  c++  java
  • LeetCode-Word Search

    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.

    You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?

    If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.

    Analysis:
    Use Trie + DFS, which is not hard. Key point here is to optimize the code. Excellent example:
    https://discuss.leetcode.com/topic/33246/java-15ms-easiest-solution-100-00
     
    Solution:
    public class Solution {
        public class TrieNode{
            TrieNode[] childs = new TrieNode[26];
            String word;
        }
        
        //int[][] moves = new int[][] { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
        public List<String> findWords(char[][] board, String[] words) {
            List<String> resList = new ArrayList<String>();
            if (board.length==0 || board[0].length==0) return resList;
            
            TrieNode root = new TrieNode();
            for (String word : words){
                addWord(root,word.toCharArray());
            }
            
            for (int i=0;i<board.length;i++)
                for (int j=0;j<board[0].length;j++)
                    if (root.childs[board[i][j]-'a']!=null){
                        findWordsRecur(board,root.childs[board[i][j]-'a'],i,j,resList);
                }
            
            return resList;
        }
        
        // Assume that board[x][y] matches curNode, starting from [x,y] search for other words whose root is curNode.
        public void findWordsRecur(char[][] board, TrieNode curNode, int x, int y, List<String> resList){
            // Find a word.
            if (curNode.word!=null){
                resList.add(curNode.word);
                // OPTIMIZATION: Set word to null for one-time add, instead of using HashSet for duplicates.
                curNode.word = null;
            }
            
            // OPTIMIZATION: Mark board[x][y] as '#' instead of using boolean[][] visited.
            char curChar = board[x][y];
            board[x][y] = '#';
            
            // OPTIMIZATION: Use four explicit conditions instead of loop and isValid function.
            if (x>0 && board[x-1][y]!='#' && curNode.childs[board[x-1][y]-'a']!=null) 
                findWordsRecur(board,curNode.childs[board[x-1][y]-'a'],x-1,y,resList);
                
            if (x<board.length-1 && board[x+1][y]!='#' && curNode.childs[board[x+1][y]-'a']!=null) 
                findWordsRecur(board,curNode.childs[board[x+1][y]-'a'],x+1,y,resList);
                
            if (y>0 && board[x][y-1]!='#' && curNode.childs[board[x][y-1]-'a']!=null) 
                findWordsRecur(board,curNode.childs[board[x][y-1]-'a'],x,y-1,resList);
                
            if (y<board[0].length-1 && board[x][y+1]!='#' && curNode.childs[board[x][y+1]-'a']!=null) 
                findWordsRecur(board,curNode.childs[board[x][y+1]-'a'],x,y+1,resList);
                
            board[x][y] = curChar;
        }
        
        /*public boolean isValid(char[][] board, int x, int y){
            return x>=0 && x<board.length && y>=0 && y<board[0].length;
        }*/
        
        public void addWord(TrieNode root, char[] word){
            for (int i=0;i<word.length;i++){
                char c = word[i];
                if (root.childs[c-'a']==null){
                    root.childs[c-'a'] = new TrieNode();
                }
                root = root.childs[c-'a'];
            }
            root.word = new StringBuilder().append(word).toString();
        }
    }
  • 相关阅读:
    玩转Android之手摸手教你DIY一个抢红包神器!
    NetWork——关于TCP协议的三次握手和四次挥手
    请保持心情快乐,请保持情绪稳定
    第八节:Task的各类Task<TResult>返回值以及通用线程的异常处理方案。
    第七节:利用CancellationTokenSource实现任务取消和利用CancellationToken类检测取消异常。
    第六节:深入研究Task实例方法ContinueWith的参数TaskContinuationOptions
    第五节:Task构造函数之TaskCreationOptions枚举处理父子线程之间的关系。
    第四节:Task的启动的四种方式以及Task、TaskFactory的线程等待和线程延续的解决方案
    第三节:ThreadPool的线程开启、线程等待、线程池的设置、定时功能
    第二节:深入剖析Thread的五大方法、数据槽、内存栅栏。
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5858639.html
Copyright © 2011-2022 走看看