题目描述:
马在中国象棋以日字形规则移动。
请编写一段程序,给定n×m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。
代码:
package lanqiao;
import java.util.*;
public class Main {
static int n,m,x,y;
static int max = 0;
static int dx[] = {1,1,-2,-1,-2,-1,2,2};
static int dy[] = {2,-2,1,2,-1,-2,1,-1};
static boolean f[][];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t -- > 0)
{
n = sc.nextInt();
m = sc.nextInt();
f = new boolean[15][15];
x = sc.nextInt();
y = sc.nextInt();
max = 0;
f[x][y] = true;
dfs(x,y,1);
System.out.println(max);
}
}
public static void dfs(int x,int y,int sum){
if(sum == n*m){
max += 1;
return;
}
for(int i = 0;i < 8;i ++){
int xx = x + dx[i];
int yy = y + dy[i];
if(xx < 0 || xx >= n || yy >= m || yy < 0 || f[xx][yy]){
continue;
}
f[xx][yy] = true;
dfs(xx,yy,sum + 1);
f[xx][yy] = false;
}
}
}