效果图

image.png
结果图

image.png
完整代码
package com.nan.recursion;
/**
* @author klr
* @create 2020-07-05-16:49
*/
public class RecursionTest {
public static void main(String[] args) {
test(5);
System.out.println("阶乘结果:");
System.out.println(factorial(5));
System.out.println("迷宫:");
int[][] map=new int[8][7];
//设置迷宫的墙
for(int i=0;i<8;i++){
map[i][0]=1;
map[i][6]=1;
}
for (int j = 0; j < 7; j++) {
map[0][j]=1;
map[7][j]=1;
}
map[3][1]=1;
map[3][2]=1;
map[4][3]=1;
map[3][4]=1;
for (int[] ints : map) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}
System.out.println("迷宫的解:");
maze(map,1,1);
for (int[] ints : map) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}
}
//递归打印n
public static void test(int n) {
if (n > 1) {
test(n - 1);
}
System.out.println("n="+n);
}
//阶乘n
public static int factorial(int n){
if (n == 1) {
return 1;
}
else {
return factorial(n-1)*n;
}
}
//递归求解迷宫
//map为地图,迷宫为8行7列
//i,j为起点
//0代表未走过,1代表墙,2代表通路可以走,3代表已走过,走不通
public static boolean maze(int[][] map,int i,int j){
//提前写死终点,也是出口
if(map[6][5]==2){
return true;
}
//如果当前结点没走过
if (map[i][j] == 0) {
//假设当前结点可以走
map[i][j]=2;
//接下来制定规则,下》右》上》左
if (maze(map, i + 1, j)) {
return true;
}
if (maze(map, i, j + 1)) {
return true;
}
if (maze(map, i - 1, j)) {
return true;
}
if (maze(map, i - 1, j)) {
return true;
}
//如果上下左右都不能走,说明map[i][j]这条路可以放弃了
else {
map[i][j] = 3;
return false;
}
}
else { //1,3,不可能是2,因为2会一直走,不然就会变成3
return false;
}
}
}
网友评论