一. 递归可以解决哪些问题
- 各种数学问题,比如:迷宫问题,八皇后问题,汉诺塔问题,阶乘问题等。
- 各种算法中也会用到递归,比如:快排,归并排序,二分查找,分治算法等。
二. 递归应该遵循的重要规则
- 执行一个方法时,就创建一个新的受保护的独立空间(栈空间)。
- 方法中局部变量是独立的,不会相互影响。
- 如果方法中使用的是引用数据类型(如数组),就会共享该引用类型的数据。
- 递归必须向退出递归的条件逼近,否则会无限递归,出现StackOverflowError.
- 当一个方法执行完毕,或者遇到return,就会返回,遵守谁调用就将结果返回谁,同时当方法执行完或者返回时,方法也就执行完毕。
三. 迷宫问题
package com.bzw.recursion;
public class Labyrinth {
public static void main(String[] args) {
//构建一个8*7的二维数组表示迷宫
//其中 “1” 表示墙 ;“0” 表示路
int[][] map = new int[8][7];
for (int i=0;i<8;i++){
for (int j=0;j<7;j++){
map[i][0] = 1;
map[i][6] = 1;
map[0][j] = 1;
map[7][j] = 1;
}
}
map[3][1] = 1;
map[3][2] = 1;
// map[2][2] = 1;
for (int i=0;i<8;i++){
for (int j=0;j<7;j++){
System.out.print(map[i][j] + " ");
}
System.out.println();
}
System.out.println("迷宫路径为:");
setWay(map,1,1);
for (int i=0;i<8;i++){
for (int j=0;j<7;j++){
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
//走迷宫 1表示墙,2表示探测过且可以走,3表示死路
//走迷宫之前得先确定策略:下->右->上->左(策略不唯一,策略与路径长度有关)
public static boolean setWay(int map[][],int i,int j){
if (map[6][5] == 2){
return true;
}else{
if (map[i][j] == 0) {
map[i][j] = 2; //先假设可以走,设置为2
if (setWay(map, i + 1, j)) {
return true;
} else if (setWay(map, i, j + 1)) {
return true;
} else if (setWay(map, i - 1, j)) {
return true;
} else if (setWay(map, i, j - 1)) {
return true;
}else {
map[i][j] = 3; //如果上下左右都不可以走,设置为3,死路
return false;}
}else {
return false;
}
}
}
}
四. 八皇后问题
package com.bzw.recursion;
public class Queen8 {
static int max = 8;
int[] array = new int[max];
static int count = 0;
static int judgeCount = 0;
public static void main(String[] args) {
Queen8 queen8 = new Queen8();
queen8.check(0);
System.out.println("一共有" + count + "种");
System.out.println("判断了" + judgeCount + "次");
}
private void check(int n){
if (n == max){ //如果n = max 说明所有皇后已经摆放完毕
print();
count++;
return;
}
for (int i=0;i<max;i++){ // i 表示皇后摆放在第几列
array[n] = i;
if (judge(n)){ //如果这里不满足摆放条件,皇后的位置向后移一位(在回溯时,皇后位置还会再变化)
check(n+1); //当一个皇后摆放完毕再摆放下一个
}
}
}
/**
*
* @param n 表示第几个皇后
* @return
* 虽然8皇后问题是在棋盘上描述的,但这里用一个一维数组表示第几个皇后及对应的位置
* 即一维数组的下标表示第几个皇后(皇后所在的行),对应的数组值表示皇后在第几列
*/
private boolean judge(int n){
judgeCount++;
for (int i=0;i<n;i++){
//皇后不能在同一列,同一斜线上(也不能在同一行,但此算法必不可能在同一行)
if (array[i] == array[n] || Math.abs(n-i) == Math.abs(array[n] - array[i])){
return false;
}
}
return true;
}
private void print(){
for (int i=0;i<array.length;i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
}
五. 总结
递归这种思想为我们在解决问题时提供了一种思路,有时候也确实能够比较好的解决问题,同时还有代码比较简洁的优点。但是,有时候虽然能用递归解决问题,但递归回溯次数太多,时间复杂度较高,并不是最优解。(八皇后问题光判断就要15720次。)