Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Scanner;
- public class WordMaker {
- private static int listSize = 0;//Determines size of the word list being read.
- public static int DEF_SIZE = 100000000;//Arbitrary size for the list of words.
- public static void main (String[] args)
- {
- char[][] graph = { { 'R','A','H', 'J', 'M' },
- { 'Y','U','W', 'W', 'K' },
- { 'R','X','N', 'F', 'M' },
- { 'Q','G','E', 'E', 'B' },
- { 'E','O','A', 'P', 'E' } };
- File dictionary = new File("dict.txt");
- String[] wordList = new String[DEF_SIZE];//String array for the file being read, stores the words we want.
- readAFile(dictionary, wordList);
- for (int i = 0; i < wordList.length; i++)
- {
- findAWord(graph, wordList[i]);
- }
- }
- //Sweeps through the char array, determines whether one of the cells matches a word.
- public static boolean findAWord(char[][] board, String word) {
- boolean result;
- for (int i = 0; i < board.length; i++)
- {
- for (int j = 0; j < board[i].length; j++)
- {
- if (board[i][j] == word.charAt(0))
- {
- result = DFS(board, word, i, j, 0);
- if (result)
- {
- return true;
- }
- }
- }
- }
- return false;
- }
- private static boolean DFS(char[][] board, String word, int i, int j, int index) {
- //If we find the word,
- if (index == word.length()) {
- return true;
- }
- //If we go out of bounds.
- if (i < 0 || i >= board.length || j < 0 || j >= board[i].length) {
- return false;
- }
- //If the current index of the char array we are looking at does not match the current character of the word we are analyzing.
- if (board[i][j] != word.charAt(index)){
- return false;
- }
- //Boolean to determine whether we have found the word or not.
- boolean result;
- board[i][j] += 1000;//Makes the current cell invalid, so it can not be used again (allows traversal of the character array).
- result = DFS(board, word, i - 1, j, index + 1)
- || DFS(board, word, i + 1, j, index + 1)
- || DFS(board, word, i, j - 1, index + 1)
- || DFS(board, word, i, j + 1, index + 1);
- board[i][j] -= 1000;//Resets the current cell, making it valid again for the next word to be found.
- return result;
- }
- //Reading a file.
- public static String[] readAFile(File fileName, String[] wordList)
- {
- try
- {
- Scanner fileScanner = new Scanner(fileName);
- while (fileScanner.hasNextLine())
- {
- if (fileScanner.next().length() >= 2 && fileScanner.next().length() <= 6)
- {
- wordList[listSize++] = fileScanner.next().toLowerCase();
- }
- }
- fileScanner.close();
- }
- catch (Exception e)
- {
- System.out.println(e);
- }
- return wordList;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement