一、思路
-
枚举8个方向,题目要求按照字典序的方向进行数组的赋值。
由于列是字母,所以以列小(列从A开始)的先枚举,然后列相同,就以行小(行从1开始)的先枚举。比如图中B3 和 B5 先枚举。//按照字典序 static int[] dx = {-1, 1, -2, 2, -2, 2, -1, 1}; static int[] dy = {-2, -2, -1, -1, 1, 1, 2, 2};
-
利用dx,dy数组进行8个方向dfs就行了,因为能走完全部的格子,所以从任意一点出发都可以,所以我们直接从(1,1)点出发即可。当步数等于 n*m 格子数 就输出路径。
二、代码
import java.util.*;
public class POJ_2488 {
static boolean[][] vis = new boolean[30][30];
static int t, n, m, top, cnt;
static String[] path = new String[1000];
//按照字典序
static int[] dx = {-1, 1, -2, 2, -2, 2, -1, 1};
static int[] dy = {-2, -2, -1, -1, 1, 1, 2, 2};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while (t-- > 0) {
n = sc.nextInt();
m = sc.nextInt();
top = 1;//清空路径
path[0] = "A1"; //起点
ok = false;
System.out.println("Scenario #" + (++cnt) +":");
dfs(1, 1, 1);
if (!ok) {
System.out.println("impossible");
}
System.out.println();
}
}
static boolean ok;
static void dfs(int x, int y, int step) {
if (ok) return; //找到结果
if (step == n * m) {
//输出路径
ok = true;
for (int i = 0; i < top; i++) {
System.out.print(path[i]);
}
System.out.println();
return;
}
vis[x][y] = true;
for (int i = 0; i < 8; i++) {
int fx = x + dx[i];
int fy = y + dy[i];
if (fx >= 1 && fy >= 1 && fx <= n && fy <= m && !vis[fx][fy]) {
path[top++] = (char)(64 + fy) + "" + fx;
dfs(fx, fy, step + 1);
top--; //回溯 因为每次一条路走到底,所以回来要讲下标减一
}
}
vis[x][y] = false;
}
}