单词搜索迷宫

来源:互联网 发布:剪辑音乐的软件 编辑:程序博客网 时间:2024/05/18 18:44

单词搜索迷宫,就是在一个二维数组中找到其中所有可以组合成单词的路径。比如:

thiswatsoahgfgdt

这是一个网格,后面代码测试的时候要输入的
蛮力算法,对于小的网格,网格中仅仅只能组成少量的单词的时候,是可以的但是对于一个四级单词表来说,就不行了。
下面我从书上找到的一些测试,用的是前缀排除法和二分查找的算法

package com.wordSearch.cc;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** *  * @author SunnyBoy * @version Time:2017年7月29日 下午3:34:34 */public class WordSearch {    private int rows;    private int columns;    private char theBoard[][];    private String[] theWords;    private BufferedReader puzzleStream;    private BufferedReader wordStream;    private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));    public static void main(String[] args) {        WordSearch p = null;        try {            p = new WordSearch();        }        catch(IOException e) {            System.out.println("IO Error: ");            e.printStackTrace();            return ;        }        System.out.println("Solving...");        System.out.println(p.solvePuzzle());    }    /**     * Constructor for WordSearch class. Prompts for and reads puzzle and dictionary     * files.     *      * @throws IOException     */    public WordSearch() throws IOException {        puzzleStream = openFile("Enter puzzle file");        wordStream = openFile("Enter dictionary name");        System.out.println("Reading files...");        readPuzzle();        readWords();    }    /**     * Routine to solve the word search puzzle. Performs checks in all eight     * directions.     *      * @return number of matches     */    public int solvePuzzle() {        int matches = 0;        for (int r = 0; r < rows; r++)            for (int c = 0; c < columns; c++)                for (int rd = -1; rd <= 1; rd++)                    for (int cd = -1; cd <= 1; cd++)                        if (rd != 0 || cd != 0)                            matches += solveDirection(r, c, rd, cd);        return matches;    }    /**     * Performs the binary search for word search.     * Return the last position examined this position     * either matches x,or x is a prefix of the mismatch,or there is     * no word for which x is a prefix.     * @param a     * @param x     * @return     */    private static int prefixSearch(String[] a, String x) {        int idx = Arrays.binarySearch(a, x);        if(idx < 0)            return -idx-1;        else return idx;    }    /**     * Print a prompt and open a file. Retry until open is successful. Program exits     * if end of file is hit.     */    private BufferedReader openFile(String message) {        String fileName = "";        FileReader theFile;        BufferedReader fileIn = null;        do {            System.out.println(message + ": ");            try {                fileName = in.readLine();                if (fileName == null)                    System.exit(0);                theFile = new FileReader(fileName);                fileIn = new BufferedReader(theFile);            } catch (IOException e) {                System.err.println("Cannot open " + fileName);            }        } while (fileIn == null);        System.out.println("Opened " + fileName);        return fileIn;    }    /**     * Routine to read the dictionary. Error message is printed if dictionary is not     * sorted.     *      * @throws IOException     */    private void readWords() throws IOException {        List<String> words = new ArrayList<String>();        String lastWord = null;        String thisWord;        while ((thisWord = wordStream.readLine()) != null) {            if (lastWord != null && thisWord.compareTo(lastWord) < 0) {                System.err.println("Dictionary is not sorted...skipping");                continue;            }            words.add(thisWord);            lastWord = thisWord;        }        theWords = new String[words.size()];        theWords = words.toArray(theWords);    }    /**     * Routine to read the grid. Checks to ensure that the grid is rectangulat.     * Checks to make sure that capacity is not exceeded is omitted.     *      * @throws IOException     */    private void readPuzzle() throws IOException {        String oneLine;        List<String> puzzleLines = new ArrayList<String>();        if ((oneLine = puzzleStream.readLine()) == null)            throw new IOException(" No lines in puzzle file");        columns = oneLine.length();        puzzleLines.add(oneLine);        while ((oneLine = puzzleStream.readLine()) != null) {            if (oneLine.length() != columns)                System.err.println(" Puzzle is not rectangular; skipping row");            else                puzzleLines.add(oneLine);        }        rows = puzzleLines.size();        theBoard = new char[rows][columns];        int r = 0;        for (String theLine : puzzleLines) {            theBoard[r++] = theLine.toCharArray();        }    }    /**     * Search the grid from a staring point and direction.     * @param baseRow     * @param baseCol     * @param rowDelta     * @param colDelta     * @return number of matches     */    private int solveDirection(int baseRow, int baseCol, int rowDelta, int colDelta) {        String charSequence = "";        int numMatches = 0;        int searchResult;        charSequence += theBoard[baseRow][baseCol];        for (int i = baseRow + rowDelta, j = baseCol + colDelta; i >= 0 && j >= 0 && i < rows                && j < columns; i += rowDelta, j += colDelta) {            charSequence += theBoard[i][j];            searchResult = prefixSearch(theWords, charSequence);            if (searchResult == theWords.length)                break;            if (!theWords[searchResult].startsWith(charSequence))                break;            if (theWords[searchResult].equals(charSequence)) {                numMatches++;                System.out.println("Found " + charSequence + " at " + baseRow + " " + baseCol + " to " + i + " " + j);            }        }        return numMatches;    }}

下面是我实现代码的运行的内容

Enter puzzle file: D:\test/hello.txtOpened D:\test/hello.txtEnter dictionary name: D:\test/newFourWord1.txtOpened D:\test/newFourWord1.txtReading files...Solving...Found this at 0 0 to 0 3Found two at 0 0 to 2 0Found hi at 0 1 to 0 2Found his at 0 1 to 0 3Found it at 0 2 to 1 2Found at at 1 1 to 0 0Found at at 1 1 to 1 2Found of at 2 0 to 3 0Found at at 2 1 to 1 2Found ad at 2 1 to 3 2Found hat at 2 2 to 0 0Found go at 3 1 to 2 0Found that at 3 3 to 0 013

如有疑问,可以一起探讨,谢谢