Missionaries and savages crossing the river (numpy, pandas)

insert image description here

Hard work is not to be mediocre~

The biggest reason for learning is to get rid of mediocrity. One day earlier, there will be more splendor in life; one day later, one day more mediocrity.

Table of contents

1. Problem description

2. Explanation of the problem

1. Algorithm analysis

2. Program Execution Process

3. Write a program to solve the problem

3. Problem thinking

1. Algorithm analysis:

2. Experiment execution process:

4. The method, purpose and significance of each step of the code

1. Import library:

2. Get input:

3. Define the data structure:

4. Determine whether the state is legal:

5. Heuristic function:

6. Determine whether the two states are the same:

7. Determine whether the current state is consistent with the parent state:

8. Sort the open list by f value:

9. Find the node in the list:

10. The main body of the A* algorithm:

11. Recursively print paths:

12. Main program:

5. In-depth research and code optimization

1. Some input situations lead to infinite loops or excessive memory consumption. In order to better handle these situations, some additional restrictions or optimization measures can be added.

2. After research, in the problem of savages and missionaries crossing the river, the following two optimization strategies are better:

3. Take limiting the search depth as an example here, you can follow the steps below:

 Six, complete code


1. Problem description

    There are N missionaries and N savages who come to the river to cross the river. There is a boat on the river bank, which can accommodate at most k people at a time. Question: For the sake of safety, how should the missionaries plan the ferry plan so that at any time, the number of savages on both sides of the river and on the boat does not exceed the number of missionaries (otherwise it is not safe, and the missionaries may be eaten by savages). That is to solve the ferry plan that satisfies M (the number of missionaries) ≥ C number of wild men) and M+C≤k at any time during the process of ferrying missionaries and wild men from the left bank to the right bank. 

2. Explanation of the problem

1. Algorithm analysis

Let M be the number of missionaries, and C be the number of savages. The process of solving this problem with state space is as follows:

M, C = N, boat = k, requires M>=C and M+C <= K

 Represented by triples (ML , CL , BL)

where 0<=ML , CL <= 3 , BL ∈ { 0 , 1}

Initial state: There are 3 savages and 3 missionaries on the left bank of the river; 0 savages and 0 missionaries on the right bank of the river; the boat stops on the left bank with 0 people on board. initial state (3, 3, 1)

Target state: 0 savages and 0 missionaries on the left bank of the river; 3 savages and 3 missionaries on the right bank of the river; the boat stops on the right bank with 0 people on board. target state (0, 0, 0)

The whole problem is abstracted as how to reach the target state from the initial state through a series of intermediate states. The state change is caused by crossing the river by rowing a boat.

Consider the left bank of the river as the base point

Pij: row the boat from the left bank to the right bank, where the first subscript i indicates the number of missionaries on board, and the second subscript j indicates the number of cannibals on board;

Qij: row the boat back from the right bank to the left bank, the subscripts are defined as before.

There are 10 operations in total, and the operation set is F={P01, P10, P11, P02, P20, Q01, Q10, Q11, Q02, Q20}

rule set

P10 if ( ML ,CL , BL=1 )   then ( ML–1 , CL , BL –1 )

P01 if ( ML ,CL , BL=1 )   then ( ML , CL–1 , BL –1 )

P11 if ( ML ,CL , BL=1 )   then ( ML–1 , CL–1 , BL –1 )

P20 if ( ML ,CL , BL=1 )   then ( ML–2 , CL , BL –1 )

P02 if ( ML ,CL , BL=1 )   then ( ML , CL–2 , BL –1 )

Q10 if ( ML ,CL , BL=0 )   then ( ML+1 , CL , BL+1 )

Q01 if ( ML ,CL , BL=0 )   then ( ML , CL+1 , BL +1 )

Q11 if ( ML ,CL , BL=0 )   then ( ML+1 , CL +1, BL +1 )

Q20 if ( ML ,CL , BL=0 )   then ( ML+2 , CL +2, BL +1 )

Q02 if ( ML ,CL , BL=0 )   then ( ML , CL +2, BL +1 )

According to the requirements, the following 5 possible river crossing schemes are obtained:

  (1) Crossing 2 Missionaries

  (2) Ferry 2 Savage

  (3) Crossing 1 Savage 1 Missionary

  (4) Crossing 1 Missionary

  (5) Crossing 1 Savage

Finding a heuristic function to guide the selection of rules

   This program needs to define state nodes, use collections to store state nodes, and use recursive thinking to find the target state.

2. Program Execution Process

The above principle is completely based on the premise that the number of missionaries and savages is 3, and the maximum passenger capacity of a ship is 2. Combining the above analysis, it is not difficult to see that when the specific number of missionaries and savages and the maximum passenger capacity of a ship have not been specified, the difference from the previous analysis is only that according to the number of people, how many passengers are there from one end of the river to the other? The method, other principle processes are all the same as the process that the number of missionaries and savages is 3, and the maximum passenger capacity of a ship is 2.

There are 32 possible states in total, as shown in Table 1.

            Table 1 All possible states of the missionary and cannibal problem

state

m, c, b

state

m, c, b

state

m, c, b

state

 m, c, b

S0

3,3,1

S8

1,3,1

S16

3,3,0

S24

1,3,0

S1

3,2,1

S9

1,2,1

S17

3,2,0

S25

1,2,0

S2

3,1,1

S10

1,1,1

S18

3,1,0

S26

1,1,0

S3

3,0,1

S11

1,0,1

S19

3,0,0

S27

1,0,0

S4

2,3,1

S12

0,3,1

S20

2,3,0

S28

0,3,0

S5

2,2,1

S13

0,2,1

S21

2,2,0

S29

0,2,0

S6

2,1,1

S14

0,1,1

S22

2,1,0

S30

0,1,0

S7

2,0,1

S15

0,0,1

S23

2,0,0

S31

0,0,0

It is worth noting that according to the conditions stipulated in the title, we should cross out the illegal state, which can speed up the efficiency of search and solution. For example, first of all, the number of cannibals on the bank exceeds that of missionaries, that is, the six states of S4, S8, S9, S20, S24, and S25 are illegal; secondly, the cannibals on the right bank should be crossed out Situations where the number exceeds monks, that is, S6, S7, S11, S22, S23, S27, etc.; among the remaining 20 legal states, there are 4 impossible states; S15 and S16 cannot appear, because the ship does not It may be docked on an uninhabited shore; S3 cannot appear, because it is impossible for the missionaries to row the boat back safely under the eyes of the cannibals who are dominant in numbers; S28 should also be rowed, because the missionaries cannot be in the number The boat was safely rowed to the opposite bank under the nose of the dominant man-eater. It can be seen that in the state space, there are only 16 reasonable states that really meet the conditions specified in the topic.

3. Write a program to solve the problem

 

3. Problem thinking

1. Algorithm analysis:

   In the problem of crossing the river between missionaries and savages, it is assumed that the number of missionaries is M, the number of savages is C, and the passenger capacity of the boat is K. The state space of the problem is as follows:

   Left Bank: M, C

   Right bank: 0, 0

   Starting position: left bank

   Initial state: There are M missionaries and C savages on the left bank, no one on the right bank, and the boat stops on the left bank.

   Target state: no one is on the left bank, there are M missionaries and C savages on the right bank, and the boat stops on the right bank.

   To solve this problem, a state space search and heuristic functions can be used. During the ship's journey from the left bank to the right bank, the passengers on board can be selected according to the following rules:

   ①Cross 2 missionaries

   ②Cross 2 savages

   ③Cross 1 savage and 1 missionary

   ④Cross 1 missionary

   ⑤ crossing 1 savage

   The program execution flow is as follows:

   ①Define the set of legal states and exclude the states that do not meet the conditions.

   ②Use state space search and recursive methods to find the target state through a series of state transitions.

   ③ According to the heuristic function, select the appropriate rules to guide the state transition.

   ④ Traverse and judge each possible state until the target state is found or a solution cannot be found.

   ⑤ Write a program to solve the problem and output the result.

2. Experiment execution process:

   ①Create a state space class, which is used to represent the state of the missionary and the savage crossing the river.

   ② Initialize the initial state and target state.

   ③Define the set of legal states and exclude the states that do not meet the conditions.

   ④ Use the depth-first search algorithm and recursive method to search for valid paths in the legal state set.

   ⑤ Realize the heuristic function and select the appropriate state transition according to the rules.

   ⑥Traverse and judge each possible state until the target state is found or a solution cannot be found.

   ⑦ Write programs to solve problems and output results.

4. The method, purpose and significance of each step of the code

1. Import library:

   

    pandas is used for data processing and outputting results.

   numpy is used to handle array operations.

2. Get input:

    

   The user enters the number of missionaries, the number of wildlings, and the maximum capacity of the ship.

3. Define the data structure:

   

  

       The child list is used to store all expanded nodes.

   open_list is used to store the nodes to be expanded.

   closed_list is used to store nodes that have been expanded.

   The State class represents the state node, including information such as the number of missionaries, the number of savages, and the position of the ship.

4. Determine whether the state is legal:

   

   The safe function is used to judge whether the state node is legal, and judge whether the constraint condition is satisfied according to certain conditions.

5. Heuristic function:

    

   The h function is a heuristic function used to evaluate the heuristic value of a node, here the product of the number of missionaries plus the number of savages minus the position of the ship and the maximum capacity of the ship is used.

6. Determine whether the two states are the same:

   The equal function is used to judge whether two state nodes are the same, and determine whether they are the same by comparing whether the attribute values ​​of the nodes are equal.

7. Determine whether the current state is consistent with the parent state:

   The back function is used to judge whether the current state node is consistent with its ancestor node, and determine whether it is consistent by backtracking and comparing the attribute values ​​of the nodes step by step.

8. Sort the open list by f value:

  The open_sort function is used to sort the nodes in the open list according to the f value.

9. Find the node in the list:

  The in_list function is used to find if there is a node identical to the given node in the list.

10. The main body of the A* algorithm:

    

 Use open_list to store nodes to be expanded, and use closed_list to store nodes that have been expanded.

    In the loop, first check whether the target node exists, if it exists, add it to the A list and remove it from the open_list.

    If open_list is empty, terminate the loop.

    Take the first node from the open_list, add it to the closed_list, and then generate new child nodes on the left and right sides according to the position of the ship.

    Check the legitimacy of the child node and whether it is consistent with the parent node, if the condition is not met, remove the child node.

    Otherwise, set the parent node of the child node, update the g and f values, and add the child node to the open_list, and then sort the open_list.

    Return the final target node set A.

11. Recursively print paths:

    The printPath function is used to recursively print the path, backtracking from the target node to the initial node, and print the attribute value of each node.

12. Main program:

  The main program first outputs the number of missionaries, the number of savages and the maximum capacity of the ship.

    Call the A_star function to obtain the final target node set final.

    Output the number of solutions.

    If solutions exist, the path to each solution is output one by one.

    If no solution is found, an appropriate prompt message is output.

5. In-depth research and code optimization

1. Some input situations lead to infinite loops or excessive memory consumption. In order to better handle these situations, some additional restrictions or optimization measures can be added.

① Limit search depth: add a search depth limit to prevent the program from searching infinitely. You can set a maximum search depth and check it during the search. If the maximum depth has been reached but no solution has been found, it can be judged that there is no solution or the search is terminated.

②Limit state repetition: record the state nodes that have been visited in the closed_list to avoid repeated visits. When expanding a node, you can first check whether the newly generated node has already appeared in the closed_list, and if so, you can skip the node.

③Optimize the heuristic function: By adjusting the calculation method of the heuristic function, it will be more accurate and efficient. The choice of heuristic function affects the efficiency of the search algorithm and the quality of the results. You can try different heuristic functions to optimize algorithm performance.

④ Pruning strategy: When generating new nodes, some conditional judgments are used to prune invalid branches. For example, if there are more wildlings on board than missionaries, then this state is invalid and can be skipped.

⑤ Use iterative deepening search: Iterative deepening search is a variant of depth-first search that gradually increases the search depth in each iteration. This approach can find solutions within a limited search depth, and it is less space-demanding than a full depth-first search.

2. After research, in the problem of savages and missionaries crossing the river, the following two optimization strategies are better:

① Limit search depth: By setting the maximum search depth, prevent the program from searching infinitely. This helps you control the execution time and resource consumption of your algorithms. You can determine the maximum search depth based on the size and complexity of your problem. If the search exceeds the maximum depth without finding a solution, it can be judged as no solution or terminate the search.

②Limit state repetition: record the state nodes that have been visited in the closed_list to avoid repeated visits. This prevents the algorithm from repeatedly cycling through invalid states. When expanding a node, first check whether the newly generated node has appeared in the closed_list, if so, you can skip the node.

Of course, which restrictive measures to use depends on the needs and actual conditions. If there are stricter requirements on the execution time of the algorithm, then limiting the search depth may be more appropriate. If the memory consumption of the algorithm is more of a concern then limiting state duplication may be more important.

3. Take limiting the search depth as an example here, you can follow the steps below:

①Add a variable to the code to indicate the maximum search depth, such as max_depth.

② Modify the A_star function to check whether the current search depth exceeds the maximum depth during the search process. The depth can be checked before entering the next level of recursion, and the search is terminated when the maximum depth is exceeded. You can add the following code snippets where appropriate:

if get.g > max_depth:

    # Exceeded the maximum depth, terminate the search

    break

③Set the value of the maximum search depth in the main function, for example max_depth = 10.

By setting the maximum search depth, the execution time and resource consumption of the algorithm can be controlled. According to the scale and complexity of the problem, the value of the maximum depth can be adjusted appropriately according to the needs.

Note that modifying the search depth is simply a limiting measure that can help control the execution time of the algorithm. But this can also lead to failure to find a solution in some cases, because there may not be enough depth to search for an optimal solution. Therefore, there is a trade-off between the time requirement and the quality of the solution when using it.

 Six, complete code

Missionaries and savages crossing the river (numpy, pandas) can be customized and input with complete code A* algorithm resource-CSDN library

Guess you like

Origin blog.csdn.net/m0_63794226/article/details/131212053