forked from nanwan03/poj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2488 A Knight's Journey.java
55 lines (54 loc) · 1.52 KB
/
2488 A Knight's Journey.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
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
private static final int[] DX = {-1,1,-2,2,-2,2,-1,1};
private static final int[] DY = {-2,-2,-1,-1,1,1,2,2};
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int testcase = in.nextInt();
for (int i = 1; i <= testcase; ++i) {
int row = in.nextInt();
int col = in.nextInt();
boolean[][] visited = new boolean[row][col];
boolean isPossible = false;
visited[0][0] = true;
List<String> items = new ArrayList<String>();
items.add("A1");
isPossible = helper(row, col, 0, 0, 1, items, visited);
StringBuilder sb = new StringBuilder();
if (isPossible) {
for (String str : items) {
sb.append(str);
}
} else {
sb.append("impossible");
}
System.out.println("Scenario #" + i + ":");
System.out.println(sb.toString() + "\n");
}
}
private static boolean helper(int row, int col, int x, int y, int num, List<String> items, boolean[][] visited) {
if (num == row * col) {
return true;
}
for (int i = 0; i < 8; ++i) {
int nx = x + DX[i];
int ny = y + DY[i];
if (nx < 0 || nx >= row || ny < 0 || ny >= col || visited[nx][ny]) {
continue;
}
items.add(new String((char)('A' + ny) + "" + (nx + 1)));
visited[nx][ny] = true;
num++;
boolean isPossible = helper(row, col, nx, ny, num, items, visited);
if (isPossible) {
return true;
}
visited[nx][ny] = false;
num--;
items.remove(items.size() - 1);
}
return false;
}
}