Simple simulation algorithm (1)

Used python library of pyautogui should know the official document has one such example:

Source as follows:

 1 import pyautogui
 2 
 3 distance = 200
 4 while distance > 0:
 5     pyautogui.dragRel(distance, 0, duration = 0.5) #
 6     distance -= 10
 7     pyautogui.dragRel(0, distance, duration = 0.5) #
 8     pyautogui.dragRel(-distance, 0, duration = 0.5) #
 9     distance -= 10
10     pyautogui.dragRel(0, -distance, duration = 0.5) #

This is similar to a matrix traversal, similar to the familiar depth-first search, when entering the matrix has been close to the wall side of the sport, then use c ++ how to implement such an algorithm it?

Defining a first matrix to hold the region:

1 const int maxn = 50;
2 int M[maxn][maxn] = {0};
3 int m_size = 1;

The maximum range is 50 * 50 matrix, of course, with the vector <int> also, the default size of a matrix. Subsequently, the search direction about the need to define the order here is the right upper → lower left → →:

1 const int array_x[] = {0, 1, 0, -1};
2 const int array_y[] = {1, 0, -1, 0};
3 int dir = 0;

Defines two direction vectors, is then used to indicate the direction of a current dir forward. Of course, in the matrix needs to determine whether the proper position, the default value of 0 indicates that we have not yet gone through location:

1 bool check(int x, int y) {
2     if (x < 0 || x >= m_size || y < 0 || y >= m_size) {
3         return false;
4     }
5     if (M[x][y] > 0) {
6         return false;
7     }
8     return true;
9 }

Finally, the definition of what method of walking in the matrix:

1 void run(int x, int y, int step = 1) {
2     if (check(x, y)) {
3         M[x][y] = step;
4         if (!check(x + array_x[dir], y + array_y[dir])) {
5             dir = (dir + 1) % 4;
6         }
7         run(x + array_x[dir], y + array_y[dir], step + 1);
8     }
9 }

As can be seen from the above, change direction each time come to an end edge of the matrix, if the next direction can go on to continue recursion. In order to facilitate walking See case of a matrix to show a specifically defined function:

1 void display() {
2     for (int i = 0; i < m_size; i++) {
3         for (int j = 0; j < m_size; j++) {
4             printf("%-3d", M[i][j]);
5         }
6         printf("\n");
7     }
8 }

Well defined above, these functions after only need to call them to order in the main function:

1 int main()
2 {
3     scanf("%d", &m_size);
4     run(0, 0);
5     display();
6     return 0;
7 }

The final run is as follows:

Guess you like

Origin www.cnblogs.com/viewts/p/11070314.html