-
Notifications
You must be signed in to change notification settings - Fork 0
/
Erudite.java
83 lines (63 loc) · 2.25 KB
/
Erudite.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.*;
import java.io.*;
public class Erudite
{
public static void main(String[] argv) {
Scanner in = new Scanner(System.in).useLocale(Locale.US);
PrintWriter out = new PrintWriter(System.out);
char table[][] = new char[4][4];
for (int i = 0; i < 4; i++) {
String s = in.next();
for (int j = 0; j < 4; j++) {
table[i][j] = s.charAt(j);
}
}
int n = in.nextInt();
while(n-- > 0) {
check(table, in.next());
}
}
public static boolean check(char[][] table, String s) {
char pattern[] = s.toCharArray();
boolean[] visited = new boolean[16];
for (int i = 0; i < 4 ; i++) {
for (int j = 0; j < 4; j++) {
warn("Start from "+ i+ " "+j);
if (dfsSearch(table, i, j, pattern, 0, visited)) {
System.out.println(s+": YES");
return true;
}
}
}
System.out.println(s+": NO");
return false;
}
public static boolean dfsSearch(char[][] table, int x, int y, char[] pattern, int patternPos, boolean[] visited) {
if (x < 0 || x > 3 || y < 0 || y > 3)
return false;
int p = y * 4 + x;
if (visited[p])
return false;
if (table[y][x] != pattern[patternPos]) {
return false;
}
if (patternPos == pattern.length-1) {
warn("FOUND! "+" "+x+" "+y+" "+patternPos);
return true;
}
warn("TRY! "+" "+x+" "+y+" "+patternPos+" "+table[y][x]);
visited[p]=true;
boolean result = dfsSearch(table, x, y - 1, pattern, patternPos+1, visited)
|| dfsSearch(table, x, y + 1, pattern, patternPos+1, visited)
|| dfsSearch(table, x + 1, y, pattern, patternPos+1, visited)
|| dfsSearch(table, x-1, y, pattern, patternPos+1,visited);
visited[p]=false;
return result;
}
public static final boolean DEBUG = false;
public static void warn(String s) {
if (DEBUG) {
System.out.println(s);
}
}
}