06-跳马
问题描述:
中国象棋半张棋盘如图1所示。马自左下角(0,0)向右上角(m,n)跳。规定只能往右跳,不准往左跳。比如图1中所示为一种跳行路线,并将路径总数打印出来。
输入格式:
只有一行:两个数n,m
输出格式:
只有一个数:总方案数total。
dfs题目
import java.util.Scanner;
//跳马
public class code06_Main {
//只能往右走
static int[] row = {2,1,-1,-2};
static int[] col = {1,2,2,1};
static int n,m;
static int res=0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
sc.close();
dfs(0,0);
System.out.println(res);
}
public static void dfs(int x,int y){
if(x==n&&y==m){
res++;
}
for(int i=0;i<4;i++){
int newX = x+row[i];
int newY = y+col[i];
if(!(newX<0||newY<0||newX>n||newY>m)){
dfs(newX,newY);
}
}
}
}
运行结果