一道可以使用Trie高级数据结构解决的算法题

Problem Statement

    

You have been given a "word search" puzzle, which consists of a rectangular grid of letters, in which several words are hidden. Each word may begin anywhere in the puzzle, and may be oriented in any straight line horizontally, vertically, or diagonally. However, the words must all go down, right, or down-right. (see examples)

You are given a String[], grid, indicating the letters in the grid to be searched. Character j of element i of grid is the letter at row i, column j. You are also given a String[], wordList, indicating the words to be found in the grid. You are to return a String[] indicating the locations of each word within the grid.

The return value should have the same number of elements as wordList. Each element of wordList corresponds to the element of the return value with the same index.

Each element of the return value should be formatted as "row col" (quotes added for clarity), where row is the 0-based row in which the first letter of the word is found, and col is the 0-based column in which the first letter of the word is found. If the same word can be found more than once, the location in the lowest-indexed row should be returned. If there is still a tie, return the location with the lowest-indexed column. If a word cannot be found in the grid, return an empty string for that element.

Definition

    
Class: WordFind
Method: findWords
Parameters: String[], String[]
Returns: String[]
Method signature: String[] findWords(String[] grid, String[] wordList)
(be sure your method is public)
    

Constraints

- grid will contain between 1 and 50 elements, inclusive.
- Each element of grid will contain between 1 and 50 characters, inclusive.
- Each element of grid will contain the same number of characters.
- Each character of each element of grid will be 'A'-'Z'.
- wordList will contain between 1 and 50 elements, inclusive.
- Each element of wordList will contain between 1 and 50 characters, inclusive.
- Each character of each element of wordList will be 'A'-'Z'.

Examples

0)
    
{"TEST",

                                    "GOAT",

                                    "BOAT"}
{"GOAT", "BOAT", "TEST"}
Returns: { "1 0",

                        "2 0",

                        "0 0" }
These words are pretty easy to find.
1)
    
{"SXXX",

                                    "XQXM",

                                    "XXLA",

                                    "XXXR"}
{"SQL", "RAM"}
Returns: { "0 0",

                        "" }
While "RAM" may be found going up at "3 3", we are only allowing words that go down and right.
2)
    
{"EASYTOFINDEAGSRVHOTCJYG",

                                    "FLVENKDHCESOXXXXFAGJKEO",

                                    "YHEDYNAIRQGIZECGXQLKDBI",

                                    "DEIJFKABAQSIHSNDLOMYJIN",

                                    "CKXINIMMNGRNSNRGIWQLWOG",

                                    "VOFQDROQGCWDKOUYRAFUCDO",

                                    "PFLXWTYKOITSURQJGEGSPGG"}
{"EASYTOFIND", "DIAG", "GOING", "THISISTOOLONGTOFITINTHISPUZZLE"}
Returns: { "0 0",

                        "1 6",

                        "0 22",

                        "" }
My Solution:
因为数据量不是很大,直接暴力搜也可以通过。但是我还是用Trie写了一种解决方案。代码如下:
  1 // Use Trie to match word text pattern
  2 public   class  Main  {
  3    public static void main( String[] args )
  4    {
  5        String[] grid={
  6                "PIYSRJFWOZ",
  7                "XMVFJYHKCX",
  8                "DYQCDELPKT",
  9                "BYYEPEDMLJ"
 10                "PJGXDHCZKC"
 11                "WCAWDYVSYP",
 12                "PFDATYSKMC"
 13                "OLCOLBOHEF"
 14                "ISCFLMSSVO",
 15                "UZALICRRGS"
 16                "ZQYWTPJGFV",
 17                "AJQHRMMJUG"
 18                "VUUATXYAIJ",
 19                "BIRTBMFMYR",
 20                "HJBGBXMHKB"
 21                "UJKJXYYEMO",
 22                "KCDPUWHACH",
 23                "CRYMRRFNMU",
 24                "GABUHJBCUT",
 25                "HNNWHSLPZG",
 26                "DZSNHRGITE"
 27                "NJGWCHCUDS",
 28                "LEUPKSMBVK"
 29                "QAXRSNOMGB",
 30                "IYPHOBFSMS",
 31                "ACBZJRQQPV"
 32                "CWPACIZXVL"
 33                "BQQVMTHEWU",
 34                "DDQNUSMMYS",
 35                "OJJNHCJALY"
 36                "HBBWIWFDQS"
 37                }
;
 38             
 39        String[] wordList = {"SNHRGIT""XPCR""E""MGVD""ZUIOPWPBDX""K""RJFW"
 40                "MM""I""VSY""AC""BSHW""KPU""Q""QJ""N""Z""YZDEJ"
 41                "CDPU""WCYAEJZNARCJJIUJQZSLFC""D""Z""DY"}
;
 42        
 43        String[]result = new WordFind().findWords(grid, wordList);
 44        forint i = 0; i < result.length; i++ )
 45        {
 46            System.out.println(result[i]);
 47        }

 48        
 49        Trie.Print();
 50    }

 51}

 52
 53 class  Trie
 54 {
 55    Trie[] node;
 56    String value;
 57    
 58    public static int TrieNodeCount = 0;
 59    public Trie()
 60    {
 61        node = new Trie[26];
 62        TrieNodeCount++;
 63    }

 64    
 65    public static void Print()
 66    {
 67        System.out.println("The amount of new Trie object is :"+TrieNodeCount);
 68    }

 69    
 70    public static Trie TrieRoot = new Trie();
 71    
 72    public static void AddWord(String word, String storeValue )
 73    {
 74        Trie Root = TrieRoot;
 75        forint start = 0; start < word.length(); start++ )
 76        {
 77            char ch = word.charAt(start);
 78            int i = (int)(ch-'A');
 79            if( Root.node[i]==null )
 80            {
 81                Root.node[i] = new Trie();
 82            }

 83            Root = Root.node[i];
 84        }

 85        if(Root.value==null)
 86        {
 87            Root.value = storeValue;
 88        }

 89    }

 90    
 91    public static String QueryWord(String word )
 92    {
 93        Trie Root = TrieRoot;
 94        forint i = 0; i < word.length(); i++ )
 95        {
 96            int num = (int)(word.charAt(i)-'A');
 97            if( Root.node == null || Root.node[num] == null )
 98            {
 99                return "";
100            }

101            
102            Root = Root.node[num];
103        }

104        
105        return Root.value;
106    }

107}

108
109 class  WordFind
110 {
111    int []ix = {1,1,0};
112    int []iy = {0,1,1};
113    public String[] findWords(String[] grid, String[] wordList)
114    {
115        int rowNum = grid.length;
116        int colNum = grid[0].length();
117        
118        int minLen = 10000;
119        int maxLen = 0;
120        forint i = 0; i < wordList.length; i++ )
121        {
122            if( wordList[i].length()>maxLen)
123            {
124                maxLen = wordList[i].length();
125            }

126            
127            if( wordList[i].length() < minLen )
128            {
129                minLen = wordList[i].length();
130            }

131        }

132
133        forint i = 0; i < rowNum; i++)
134        {
135            forint j = 0; j < colNum; j++ )
136            {
137                forint k = 0; k < 3; k++ )
138                {
139                    StringBuffer sb = new StringBuffer();
140                    sb.append(grid[i].charAt(j));
141                    if(1==minLen )
142                    {
143                        Trie.AddWord(sb.toString(), i+" "+j); 
144                    }

145                    
146                    forint start = 1; start < maxLen; start++ )
147                    {
148                        int x = i+ix[k]*start;
149                        int y = j+iy[k]*start;
150                        if( x >= rowNum || y >= colNum )break;
151                        
152                        sb.append(grid[x].charAt(y));
153                        
154                        String temp = sb.toString();
155                        if(temp.length()>=minLen )
156                        {
157                            Trie.AddWord(temp, i+" "+j); 
158                        }

159                    }

160                }

161            }

162        }

163        
164        String[]result = new String[wordList.length];
165        for(int i = 0; i < wordList.length;i++)
166        {
167            result[i] = Trie.QueryWord(wordList[i]);
168        }

169        
170        return result;
171    }

172}

173

你可能感兴趣的:(数据结构)