Find a word in the grid

Source: Internet
Author: User

Use a known Word table in a grid to find all the words that appear in the word list

The code is as follows

Use Java to write import Java.util.arraylist;import Java.util.treeset;public class grid Find the word {//store the set of words to find static treeset< String> ts=new treeset<string> ()///Letter grid static char[][] word={{' t ', ' h ', ' I ', ' s '},{' W ', ' A ', ' t ', ' s '},{' o ', ' a ' , ' H ', ' G '},{' f ', ' G ', ' d ', ' t '}};//used to add letters, compose the word static StringBuilder sb=new StringBuilder ();//Save coordinate information static StringBuilder sbcoor=new StringBuilder ();//Save the coordinate information of the found word and the word static arraylist<string> coorandword=new Arraylist<string> ();p ublic static void Main (string[] args) {//Add the word you are looking for ts.add ("that"), Ts.add ("This"), Ts.add (" Ts.add ("fat"); for (int i=0;i<word.length;i++) for (int. j=0;j<word[0].length;j++) for (int x=-1;x<=1;x++ ) for (int y=-1;y<=1;y++) {if (x==0 && y==0) continue;if (0<=i+x && 0<=j+y && i+x<word[ 0].length && j+y<word.length) Findword (i,j,x,y);//clear, New sb=new StringBuilder (); Sbcoor=new StringBuilder ( );} Outputs the results found SYSTEM.OUT.PRINTLN (Coorandword);} public static void Findword (int bx,int by,int x,int y) {Sb.appenD (Word[bx][by]); Sbcoor.append ("(" +bx+ "," +by+ "), if (Ts.contains ())//If the Word table to be found contains the contents of SB, Save coordinate information and words coorandword.add (sbcoor.tostring () + "--" +sb.tostring ()); if (0<=bx+x && 0<=by+y & & Bx+x<word[0].length && by+y<word.length) Findword (bx+x,by+y,x,y);}} The above run results output [(0,0) (0,1) (0,2) (0,3)-->this, (0,0) (1,0) (2,0)-->two, (3,0) (2,1) (min)-->fat, (3,3) (2,2) (+) (0,0) -->that]


Find a word in the grid

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.