Guest User

Untitled

a guest
May 27th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Scanner;
  5.  
  6. public class FBJSolve {
  7.  
  8. public static List<String> words = new ArrayList<String>();
  9. public static char[][] grid;
  10. public static boolean[][] visited;
  11. public static int size;
  12.  
  13. public static void main(String[] args) throws Exception {
  14. Scanner s = new Scanner(new File("ospd3.txt"));
  15.  
  16. while (s.hasNext()) {
  17. String word = s.next();
  18. if (word.length() < 3) continue;
  19. words.add(word);
  20. }
  21.  
  22. size = Integer.parseInt(args[0]);
  23. grid = new char[size][size];
  24. visited = new boolean[size][size];
  25.  
  26. Scanner ins = new Scanner(System.in);
  27. for(int i=0;i<size;i++) {
  28. String line = ins.nextLine();
  29. for(int j=0;j<size;j++)
  30. grid[i][j] = line.charAt(j);
  31. }
  32.  
  33. // for each word attempt to match
  34. nextWord:
  35. for (String word : words) {
  36. for(int i=0;i<size;i++)
  37. for(int j=0;j<size;j++) {
  38. if( canMatch(word, 0, i,j) ) {
  39. System.out.println(word);
  40. continue nextWord;
  41. }
  42. }
  43. }
  44. }
  45.  
  46. public static boolean canMatch(String word, int offset, int row, int col) {
  47. if (offset >= word.length())
  48. return true;
  49. if (row < 0 || row >= size || col < 0 || col >= size)
  50. return false;
  51. if (visited[row][col] || grid[row][col] != word.charAt(offset))
  52. return false;
  53.  
  54. boolean matched = false;
  55. visited[row][col] = true;
  56. matched |= canMatch(word, offset+1, row-1, col-1);
  57. matched |= canMatch(word, offset+1, row-1, col+1);
  58. matched |= canMatch(word, offset+1, row+1, col-1);
  59. matched |= canMatch(word, offset+1, row+1, col+1);
  60. matched |= canMatch(word, offset+1, row-1, col);
  61. matched |= canMatch(word, offset+1, row, col-1);
  62. matched |= canMatch(word, offset+1, row+1, col);
  63. matched |= canMatch(word, offset+1, row, col+1);
  64. visited[row][col] = false;
  65. return matched;
  66. }
  67. }
Add Comment
Please, Sign In to add comment