Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- public class FBJSolve {
- public static List<String> words = new ArrayList<String>();
- public static char[][] grid;
- public static boolean[][] visited;
- public static int size;
- public static void main(String[] args) throws Exception {
- Scanner s = new Scanner(new File("ospd3.txt"));
- while (s.hasNext()) {
- String word = s.next();
- if (word.length() < 3) continue;
- words.add(word);
- }
- size = Integer.parseInt(args[0]);
- grid = new char[size][size];
- visited = new boolean[size][size];
- Scanner ins = new Scanner(System.in);
- for(int i=0;i<size;i++) {
- String line = ins.nextLine();
- for(int j=0;j<size;j++)
- grid[i][j] = line.charAt(j);
- }
- // for each word attempt to match
- nextWord:
- for (String word : words) {
- for(int i=0;i<size;i++)
- for(int j=0;j<size;j++) {
- if( canMatch(word, 0, i,j) ) {
- System.out.println(word);
- continue nextWord;
- }
- }
- }
- }
- public static boolean canMatch(String word, int offset, int row, int col) {
- if (offset >= word.length())
- return true;
- if (row < 0 || row >= size || col < 0 || col >= size)
- return false;
- if (visited[row][col] || grid[row][col] != word.charAt(offset))
- return false;
- boolean matched = false;
- visited[row][col] = true;
- matched |= canMatch(word, offset+1, row-1, col-1);
- matched |= canMatch(word, offset+1, row-1, col+1);
- matched |= canMatch(word, offset+1, row+1, col-1);
- matched |= canMatch(word, offset+1, row+1, col+1);
- matched |= canMatch(word, offset+1, row-1, col);
- matched |= canMatch(word, offset+1, row, col-1);
- matched |= canMatch(word, offset+1, row+1, col);
- matched |= canMatch(word, offset+1, row, col+1);
- visited[row][col] = false;
- return matched;
- }
- }
Add Comment
Please, Sign In to add comment