-
Notifications
You must be signed in to change notification settings - Fork 0
/
KnightSearch.java
89 lines (63 loc) · 1.82 KB
/
KnightSearch.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
84
85
86
87
88
89
// open.kattis.com/problems/knightsearch
import java.util.PriorityQueue;
import java.util.Scanner;
public class KnightSearch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String s = in.nextLine();
char[][] board = new char[n][n];
for (int i = 0; i < s.length(); i++) {
board[i/n][i%n] = s.charAt(i);
}
String ans = "NO";
String goal = "ICPCASIASG";
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
if (board[r][c] == 'I') {
PriorityQueue<Node> q = new PriorityQueue<>();
q.add(new Node(r, c, 1));
while (!q.isEmpty()) {
Node no = q.remove();
if (no.r < 0 || no.r >= n || no.c < 0 || no.c >= n) {
continue;
}
if (board[no.r][no.c] != goal.charAt(no.steps-1)) {
continue;
}
if (no.steps == goal.length()) {
ans = "YES";
r = n;
c = n;
break;
}
int steps = no.steps+1;
q.add(new Node(no.r - 2, no.c - 1, steps));
q.add(new Node(no.r - 2, no.c + 1, steps));
q.add(new Node(no.r - 1, no.c - 2, steps));
q.add(new Node(no.r - 1, no.c + 2, steps));
q.add(new Node(no.r + 1, no.c - 2, steps));
q.add(new Node(no.r + 1, no.c + 2, steps));
q.add(new Node(no.r + 2, no.c - 1, steps));
q.add(new Node(no.r + 2, no.c + 1, steps));
}
}
}
}
System.out.println(ans);
}
static class Node implements Comparable<Node> {
int r;
int c;
int steps;
public Node(int r, int c, int steps) {
this.r = r;
this.c = c;
this.steps = steps;
}
public int compareTo(Node b) {
return steps - b.steps;
}
}
}