Previously, I used DFS to do this, and the result timed out. I did it only after reading other people's practices. Now I am using BFS. It is obvious that it is much easier to use BFS.
# Include <iostream> # include <stdio. h> # include <string. h ># include <queue> using namespace std; char map [105] [105]; int v [105] [105]; // record the minimum number of turns at the start point to reach each point. int d [4] [2] ={{}, {-}, {0,-1 }, {0, 1 }}; int begin_x, begin_y, end_x, end_y; int flag, n, m, num; struct node {int x, y; int change_d; // record the number of times to change the direction int d; // record direction}; void bfs () {queue <node> q; node s, temp; s. x = begin_x; s. y = begin_y; s. change_d = 0; s. d =-1; v [s. x] [S. y] = 0; // number of turns at the starting point q. push (s); while (! Q. empty () {temp = q. front (); q. pop (); if (temp. x = end_x & temp. y = end_y & temp. change_d <= num) {printf ("yes \ n"); flag = 1; return;} for (int I = 0; I <4; I ++) {s = temp; s. x + = d [I] [0]; s. y + = d [I] [1]; if (s. x <0 | s. x> = n | s. y <0 | s. y> = m | map [s. x] [s. y] = '*') continue;/* s. d! =-1 indicates that it is not at the starting point and can be in any direction at the starting point. The number of turns does not increase */if (s. d! =-1 & I! = S. d) // I = 0, 1, and 2 indicate s in different directions, respectively. change_d ++; s. d = I; if (s. change_d> num) continue; if (s. change_d <= v [s. x] [s. y]) {v [s. x] [s. y] = s. change_d; q. push (s) ;}}} int main () {// freopen ("in.txt", "r", stdin); int I, T; scanf ("% d", & T); while (T --) {scanf ("% d", & n, & m); for (I = 0; I <n; I ++) scanf ("% s", map [I]); scanf ("% d", & num, & begin_y, & begin_x, & end_y, & end_x); begin_x --; begin_y --; end_x --; end_y --; // The rows and columns in the question are calculated from 1, not from 0 memset (v, 1, sizeof (v )); // first initialize the number of turns. The maximum value is flag = 0; bfs (); if (! Flag) printf ("no \ n");} return 0 ;}