Article directory
recursion
simple recursive analysis
The output is 2 3 4
output is 2
Recursive Problem Solving App
Important principles to follow with recursion
maze problem
Code
package digui;
public class MiGong {
public static void main(String[] args) {
//先创建一个二维数组模拟迷宫
//地图声明
int[][] map = new int[8][7];
//使用1表示
//上下全部置为1
for (int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}
//左右全部置为1
for (int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
//设置挡板 1表示
map[3][1] = 1;
map[3][2] = 1;
//输出地图
System.out.println("地图的情况:");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.printf(map[i][j]+" ");
}
System.out.println();
}
//使用递归回溯给小球找路
setWay(map,1,1);
//输出新地图 小球走过 并标识过的递归
System.out.println("小球走过 并标识过的地图情况:");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.printf(map[i][j]+" ");
}
System.out.println();
}
}
//使用递归回溯来给小球找路
//1.map 表示地图
//2.i j表示从地图哪个为止开始出发
//3.如果小球能到map[6][5]为止 则说明通路找到
//4.约定 当map[i][j]为0表示该点没有走过;2表示路可以走;3表示该点已经走过 但是走不通
//5.在走迷宫时 需要确定一个策略:下 右 上 左,如果该点走不通 再回溯
/**
*
* @param map 表示地图
* @param i 从哪个位置开始找
* @param j
* @return 如果找到通路 则返回true
*/
public static boolean setWay(int[][] map,int i,int j){
if (map[6][5] == 2){
//通路已经找到ok
return true;
}else {
if (map[i][j] == 0){
//如果当前这个点还没走过
//按照策略 下 有 上 左 走
map[i][j] = 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;
return false;
}
}else {
//如果map[i][j] != 0 可能是1 2 3
return false;
}
}
}
}
If the new baffle map[2][2] is output
The Introduction of the Shortest Path in the Maze Problem
Change the strategy to top right bottom left
eight queens problem
Idea analysis
time complexity
Two ways to measure program execution time
time frequency
Simplified time complexity formula
ignore constant terms
ignore lower order terms
Ignore the coefficients (conditional
Calculation of Time Complexity
common time complexity
Constant order O(1)
Logarithmic order O(log2n)
Linear order O(n)
Linear-logarithmic order O(nlogN)
Square order O(n 2 )
Cubic order O(n 3 ) Kth order O(n k )