问题描述
在那个过河卒逃过了马的控制以超级超级多的走法走到了终点之后,这匹马表示它不开心了……
于是,终于有一天,它也过河了!
由于过河马积累了许多的怨念,所以这次它过了河之后,再也没有什么东西可以限制它,它可以自由自在的在棋盘上驰骋。一开始,它是在一个n行m列棋盘的左下角(1,1)的位置,它想要走到终点右上角(n,m)的位置。而众所周知,马是要走日子格的。可是这匹马在积累了这么多怨念之后,它再也不想走回头路——也就是说,它只会朝向上的方向跳,不会朝向下的方向跳。
那么,这匹马它也想知道,它想从起点跳到终点,一共有多少种走法呢?
输入格式
第一行两个数n,m,表示一个n行m列的棋盘,马最初是在左下角(1,1)的位置,终点在右上角(n,m)的位置。
输出格式
输出有一行,一个数表示走法数。由于答案可能很大,所以输出答案除以1000000007所得的余数即可。
样例输入
4 4
样例输出
2
数据规模和约定
n<=100,m<=100
思路1 DFS (40分)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main{
static int dx[] = {0, 2, 1, 2, 1};
static int dy[] = {0, 1, 2, -1, -2};
static int n, m;
static int mod = (int) (1e9 + 7);
public static void main(String[] args) throws IOException {
n = sc.nextInt();
m = sc.nextInt();
dfs(1, 1);
System.out.println(max);
}
static long max = 0;
static void dfs(int x, int y) {
if (x < 1 || y < 1 || x > n || y > m) {
return;
}
if (x == n && y == m) {
max++;
max %= mod;
return;
}
for (int i = 1; i <= 4; i++) {
dfs(x + dx[i], y + dy[i]);
}
}
static class sc {
private static StreamTokenizer input = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static int nextInt() throws IOException {
input.nextToken();
return (int) input.nval;
}
public static long nextLong() throws IOException {
input.nextToken();
return (long) input.nval;
}
}
}
思路2 递推(100分)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
long a[][] = new long[n + 1][m + 1];
//初始化
a[1][1] = 1;
int mod = (int) (1e9 + 7);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i - 1 >= 1 && j - 2 >= 1) {
a[i][j] += (a[i - 1][j - 2]) % mod;
}
if (i - 2 >= 1 && j - 1 >= 1) {
a[i][j] += (a[i - 2][j - 1]) % mod;
}
if (i - 1 >= 1 && j + 2 <= m) {
a[i][j] += (a[i - 1][j + 2]) % mod;
}
if (i - 2 >= 1 && j + 1 <= m) {
a[i][j] += (a[i - 2][j + 1]) % mod;
}
}
}
System.out.println(a[n][m] % mod);
}
static class sc {
private static StreamTokenizer input = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static int nextInt() throws IOException {
input.nextToken();
return (int) input.nval;
}
public static long nextLong() throws IOException {
input.nextToken();
return (long) input.nval;
}
}
}