Leetcode-word Search

Source: Internet
Author: User

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must is constructed from letters of sequentially adjacent cell, where "adjacent" cells is those horizontally or Vertically neighboring. The same letter cell is 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 this all inputs is 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 isn't 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? How about a Trie? If you would a-learn how to implement a basic trie, please work on the This problem:implement trie (Prefix Tree) first.

Analysis:use Trie + DFS, which is no hard. Key point, here are to optimize the code. Excellent example:https://discuss.leetcode.com/topic/33246/java-15ms-easiest-solution-100-00 solution:
 Public classSolution { Public classtrienode{trienode[] Childs=NewTrienode[26];    String Word; }        //int[][] moves = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0,-1}};     PublicList<string> Findwords (Char[] board, string[] words) {List<String> reslist =NewArraylist<string>(); if(board.length==0 | | board[0].length==0)returnreslist; Trienode Root=NewTrienode ();  for(String word:words) {Addword (Root,word.tochararray ()); }                 for(inti=0;i<board.length;i++)             for(intj=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); }                returnreslist; }        //assume that board[x][y] matches Curnode, starting from [x, Y] search for other words whose root is curnode.     Public voidFindwordsrecur (Char[] board, Trienode Curnode,intXintY, 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 the using HashSet for duplicates.Curnode.word =NULL; }                //Optimization:mark Board[x][y] as ' # ' instead of using boolean[][] visited.        CharCurchar =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&    Gt;=0 && y<board[0].length; }*/         Public voidAddword (Trienode root,Char[] word) {         for(inti=0;i<word.length;i++){            Charc =Word[i]; if(root.childs[c-' a ']==NULL) {Root.childs[c-' a '] =NewTrienode (); } Root= root.childs[c-' A ']; } Root.word=NewStringBuilder (). append (Word). toString (); }}

Leetcode-word Search

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.