当前位置:网站首页>Recursion (maze problem, Queen 8 problem)
Recursion (maze problem, Queen 8 problem)
2022-07-02 06:48:00 【I think starfish_ ninety-eight】
recursive
Recursion is a method that calls itself , Different variables are passed in each call . Recursion helps programmers solve complex problems , At the same time, it can make the code concise
Rules to follow
- When executing a method , Just create one New protected independent space ( Stack space )
- The local variables of the method are independent , Will not affect each other . If a reference type variable is used in the method ( For example, array ), Will share data of this reference type
- Recursion must be directed to Conditional approximation of exit recursion , Otherwise, infinite recursion , To die ( appear StackOverflowError Stack overflow exception )
- When a method is executed , Or meet return, It will return , Follow who calls , Return the result to , At the same time, when the method is executed or returned , The method is executed .
solve the problem
- Various mathematical problems such as : 8 queens problem , Hanoi , Factorial problem , Maze problem , The ball and basket problem (google Programming Contest )
- Recursion is also used in various algorithms , Like fast row. , Merge sort , Two points search , Divide and conquer algorithm, etc
- Problems to be solved with stacks –> Recursive code is simpler
The illustration
- According to the following code
- Deep understanding of recursion to open up stack space , And pay attention to the direction of the program ( First look at the red arrow , Look at the black arrow )
Code
package com.atguigu.recursion;
//author qij
public class RecursionTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
// By printing questions , Review the recursive invocation mechanism
//test(4);
int res = factorial(3);
//System.out.println("res=" + res);
}
// recursive : Printing problems
// The focus is on two kinds of output :
// Yes else Judge output 2
// nothing else Output 2,3,4( Look at the diagram )
public static void test(int n) {
if (n > 2) {
test(n - 1);
}
// Output :
//n=2
// else{
// System.out.println("n=" + n);
// }
// Output :
//n=2
//n=3
//n=4
System.out.println("n=" + n);
}
// Factorial problem
// The key is factorial(n - 1) Call to
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return factorial(n - 1) * n; // 1 * 2 * 3
}
}
}
Maze problem
Code
package com.atguigu.recursion;
//author qij
public class MiGong {
public static void main(String[] args) {
// First, create a two-dimensional array , Simulated maze
// Map
int[][] map = new int[8][7];
// Use 1 Represents a wall
// Set all up and down to 1
for (int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}
// Left and right are all set to 1
for (int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
// Set the baffle , 1 Express
map[3][1] = 1;
map[3][2] = 1;
// map[1][2] = 1;
// map[2][2] = 1;
// Output map
System.out.println(" The situation of the map ");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
// Using recursive backtracking to find the way for the ball
setWay(map, 1, 1);
// setWay2(map, 1, 1);
// Output a new map , The ball goes by , And marked recursion
System.out.println(" The ball goes by , And marked The situation of the map ");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
// Using recursive backtracking to find the way for the ball
// explain
//1. map Represents a map
//2. i,j Start from where on the map (1,1)
//3. If the ball can reach map[6][5] Location , It means that the path has been found .
//4. Appointment : When map[i][j] by 0 It means that the point has not been passed When it comes to 1 Represents a wall ; 2 It means the passage can go ; 3 Indicates that the point has passed , But it doesn't work
//5. In the maze , There needs to be a strategy ( Method ) Next -> Right -> On -> Left , If that doesn't work , Backtracking
/** * * @param map Represents a map * @param i Where to start looking for * @param j * @return If you find access , Just go back to true, Otherwise return to false */
public static boolean setWay(int[][] map, int i, int j) {
if(map[6][5] == 2) {
// Access has been found ok
return true;
} else {
if(map[i][j] == 0) {
// If the current point has not been passed
// According to the strategy Next -> Right -> On -> Left go
map[i][j] = 2; // Suppose that the point is accessible .
if(setWay(map, i+1, j)) {
// Go down
return true;
} else if (setWay(map, i, j+1)) {
// turn right
return true;
} else if (setWay(map, i-1, j)) {
// Up
return true;
} else if (setWay(map, i, j-1)){
// turn left
return true;
} else {
// It shows that this point is not feasible , It's a dead end
map[i][j] = 3;
return false;
}
} else {
// If map[i][j] != 0 , May be 1, 2, 3
return false;
}
}
}
// Modify the pathfinding strategy , Change to On -> Right -> Next -> Left
public static boolean setWay2(int[][] map, int i, int j) {
if(map[6][5] == 2) {
// Access has been found ok
return true;
} else {
if(map[i][j] == 0) {
// If the current point has not been passed
// According to the strategy On -> Right -> Next -> Left
map[i][j] = 2; // Suppose that the point is accessible .
if(setWay2(map, i-1, j)) {
// Go up
return true;
} else if (setWay2(map, i, j+1)) {
// turn right
return true;
} else if (setWay2(map, i+1, j)) {
// Down
return true;
} else if (setWay2(map, i, j-1)){
// turn left
return true;
} else {
// It shows that this point is not feasible , It's a dead end
map[i][j] = 3;
return false;
}
} else {
// If map[i][j] != 0 , May be 1, 2, 3
return false;
}
}
}
}
Eight queens question
Ideas
The first queen put the first row first column
The second queen is in the second row, the first column 、 And decide whether or not OK[ That is, judgment is conflict ], If you don't OK, Keep it in the second column 、 The third column 、 Put all the columns in order , Find a fit
Continue with the third queen , Or the first column 、 Second column …… Until the first 8 A queen can also be placed in a non conflict position , A correct solution has been found
When we get a correct solution , When the stack goes back to the previous stack , It's going to start going back , About to be the first queen , Put all the correct solutions in the first column , Get it all .
Then go back to the first queen and put in the second column , Continue the loop later 1,2,3,4 Steps for
Code
package com.atguigu.recursion;
//author qij
public class Queue8 {
// Define a max How many queens are there
int max = 8;
// Define an array array, Save the result of the Queen's placement , such as arr = {0 , 4, 7, 5, 2, 6, 1, 3}
int[] array = new int[max];
static int count = 0;
static int judgeCount = 0;
public static void main(String[] args) {
// Test one , 8 Is the queen right
Queue8 queue8 = new Queue8();
queue8.check(0);
System.out.printf(" Altogether %d solution ", count);
System.out.printf(" Judge the number of conflicts %d Time ", judgeCount); // 1.5w
}
// Write a method , Place the second n A queen
// Particular attention : check yes Every time you recurs , Enter into check There are for(int i = 0; i < max; i++), So there will be backtracking
private void check(int n) {
if(n == max) {
//n = 8 , Actually 8 A queen is put away (n The value range is 0-7), At this point, the output is ok
print();
return;
}
// Put the queen in turn , And determine if there is a conflict
for(int i = 0; i < max; i++) {
// First of all, the current queen n , Put it at the end of the line 1 Column
array[n] = i;
// Judge when placing the n A queen to i Column time , Conflict or not
if(judge(n)) {
// No conflict
// Go on n+1 A queen , It starts recursion
check(n+1); //
}
// If conflict , Continue to implement array[n] = i, It's going to be n A queen , Place in a backward position of the line
}
}
// See when we put the second n A queen , Check whether the queen conflicts with the queen placed in front of it
/** * * @param n It means the first one n A queen * @return */
private boolean judge(int n) {
judgeCount++;
for(int i = 0; i < n; i++) {
// explain
//1. array[i] == array[n] Said judgment The first n Whether the queen and the front n-1 The queens are in the same line
//2. Math.abs(n-i) == Math.abs(array[n] - array[i]) Means to judge the n Whether a queen and the second i Is the queen on the same slash
//abs It's absolute value ; If slash , Line subtraction = Column subtraction
//3. Judge if it's on the same line , There is no need to ,n It's increasing every time
if(array[i] == array[n] || Math.abs(n-i) == Math.abs(array[n] - array[i]) ) {
return false;
}
}
return true;
}
// Write a method , You can output the position of the queen
private void print() {
count++;
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
边栏推荐
- How to try catch statements that return promise objects in JS
- Sentinel rules persist to Nacos
- unittest.TextTestRunner不生成txt测试报告
- 部署api_automation_test过程中遇到的问题
- Self cultivation of programmers - Reflection on job hunting
- Win10: add or delete boot items, and add user-defined boot files to boot items
- kali最新更新指南
- Alibaba cloud MFA binding Chrome browser
- Function execution space specifier in CUDA
- Eggjs -typeorm treeenity practice
猜你喜欢
查询GPU时无进程运行,但是显存却被占用了
ZZQ的博客目录--更新于20210601
自学table au
[literature reading and thought notes 13] unprocessing images for learned raw denoising
Alibaba cloud MFA binding Chrome browser
20201002 VS 2019 QT5.14 开发的程序打包
Latex在VSCODE中编译中文,使用中文路径问题解决
Win10网络图标消失,网络图标变成灰色,打开网络设置闪退等问题解决
由于不正常断电导致的unexpected inconsistency;RUN fsck MANUALLY问题已解决
Pytest (1) case collection rules
随机推荐
CUDA and Direct3D consistency
Latex参考文献引用失败 报错 LaTeX Warning: Citation “*****” on page y undefined on input line *
There is no way to drag the win10 desktop icon (you can select it, open it, delete it, create it, etc., but you can't drag it)
Name six schemes to realize delayed messages at one go
ModuleNotFoundError: No module named ‘jieba. analyse‘; ‘ jieba‘ is not a package
2020-9-23 use of QT timer qtimer class.
Idea announced a new default UI, which is too refreshing (including the application link)
Utilisation de la carte et de foreach dans JS
Self study table Au
【文献阅读与想法笔记13】 Unprocessing Images for Learned Raw Denoising
Kali latest update Guide
蚂蚁集团g6初探
sprintf_ How to use s
微信小程序基础
20201025 Visual Studio2019 QT5.14 信号和槽功能的使用
Tensorrt command line program
Improve user experience defensive programming
查询GPU时无进程运行,但是显存却被占用了
Latex 编译报错 I found no \bibstyle & \bibdata & \citation command
自学table au