振兴中华
题目描述
小明参加了学校的趣味运动会,其中的一个项目是:跳格子。地上画着一些格子,每个格子里写一个字,如下所示:
从我做起振
我做起振兴
做起振兴中
起振兴中华
比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。 要求跳过的路线刚好构成“从我做起振兴中华”这句话。
请你帮助小明算一算他一共有多少种可能的跳跃路线呢?
答案是一个整数,请通过浏览器直接提交该数字。
注意:不要提交解答过程,或其它辅助说明类的内容。
解题思路:
- 使用深度搜索DFS,总路线=向下路线+向右路线。
- 使用回溯法,在不越界情况下不断递归,满足条件则+1 。
深度搜索法
public class Main {
public static void main(String[] args) {
System.out.println(dfs(0, 0));
}
public static int dfs(int i, int j) {
if (i == 3 || j == 4) {
return 1;
}
return dfs(i + 1, j) + dfs(i, j + 1); //35
}
}
回溯法
public class Main {
public static char[][] nums = {{'从', '我', '做', '起', '振'},
{'我', '做', '起', '振', '兴'},
{'做', '起', '振', '兴', '中'},
{'起', '振', '兴', '中', '华'}};
public static int ans = 0;
public static void main(String[] args) {
char[] list = new char[8];
dfs(0, 0, 0, list);
System.out.println(ans);//35
}
public static void dfs(int jump, int x, int y, char[] list) {
if (jump > 7)
return;
if (x > 3)
return;
if (y > 4)
return;
list[jump] = nums[x][y];
if (jump == 7) {
if ("从我做起振兴中华".equals(String.valueOf(list))) {
ans = ans + 1;
}
}
dfs(jump + 1, x + 1, y, list);
dfs(jump + 1, x, y + 1, list);
}
}