递归,迷宫回溯,八皇后
1.迷宫回溯
注意理解回溯,简单来说就是如果下一个位置走不通后,会返回到上一个地方在对其他情况进行判断,会循环所有的情况 递归可以理解为一个程序反复调用自己本身,像一个有终止条件的循环
package datastructure.recursion;
public class Maze {
public static void main(String[] args) {
int[][] maze = new int[8][7];
for (int i = 0; i < 7; i++) {
maze[0][i] = 1;
maze[7][i] = 1;
}
for (int i = 0; i < 8; i++) {
maze[i][0] = 1;
maze[i][6] = 1;
}
maze[3][1] = 1;
maze[3][2] = 1;
getMazeWay(1,1,maze);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(maze[i][j]+" ");
}
System.out.println();
}
}
public static boolean getMazeWay(int x, int y, int[][] maze){
if (maze[6][5] == 2){
return true;
}else {
if (maze[x][y] == 0) {
maze[x][y] = 2;
if (getMazeWay(x+1,y,maze)){
return true;
}else if (getMazeWay(x,y+1,maze)){
return true;
}else if (getMazeWay(x-1,y,maze)){
return true;
}else if (getMazeWay(x,y-1,maze)){
return true;
}else {
maze[x][y] = 3;
return false;
}
}else {
return false;
}
}
}
}
2.八皇后算法
package datastructure.recursion;
public class EightQueen {
static int max = 8;
static int[] queens = new int[max];
static int count;
static int checkCount;
public static void main(String[] args) {
check(0);
System.out.printf("一共有%d种方法",count);
System.out.printf("一共判断了%d次",checkCount);
}
public static void check(int n){
if (n == max){
showQueen();
return;
}
for (int i = 0; i < max; i++) {
queens[n] = i;
if (judge(n)){
check(n+1);
}
}
}
public static boolean judge(int n){
checkCount++;
for (int i = 0; i < n; i++) {
if (queens[n] == queens[i] || Math.abs(n-i) == Math.abs(queens[n] - queens[i])){
return false;
}
}
return true;
}
public static void showQueen(){
count++;
for (int queen : queens) {
System.out.print(queen + "");
}
System.out.println();
}
}
|