TOJ 1702.A Knight's Journey, toj1702.a
Problem description:
There is A p * q board, A knight (the horse in Chinese chess) wants to finish all the grids, and the Board is... Z (where p starts from A), vertical is 1... q.
Original question link: http://acm.tju.edu.cn/toj/showp1702.html
Solution:
DFS: The Deep Search considers all the situations. When the server guard goes out of the Board or goes to the previous lattice, the trip fails; when the number of squares that the server guard can continue to walk is equal to p * q, the trip is successful.
There is always a problem during the submission process so that this code remains WA, and finally it is found that the input of p and q is reversed, the first input number is q (vertical digit )...
Source code:
1/* 2 OJ: TOJ 3 ID: 3013216109 4 TASK: 1702.A Knight's Journey 5 LANG: C ++ 6 NOTE: DFS 7 */8 # include <cstdio> 9 # include <cstring> 10 11 int n, p, q, flag; 12 int x [8] = {-2, -2,-1,-, 2}; 13 int y [8] = }; 14 char tmp [27] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; 15 char ans1 [27]; 16 int ans2 [27]; 17 int visited [35] [35]; 18 19 bool dfs (int a, int B) {20 if (! Visited [a] [B]) visited [a] [B] = 1; 21 else return false; // if you go to the traveled chessboard, 22 ans1 [flag] = tmp [A-1]; 23 ans2 [flag] = B; 24 flag ++; 25 if (flag> = p * q) return true; // After finishing all the grids, 26 for (int I = 0; I <8; I ++) is successful) {27 if (a + x [I]> 0 & a + x [I] <= p & B + y [I]> 0 & B + y [I] <= q & dfs (a + x [I], B + y [I]) 28 return true; // if the next step does not go out of the chessboard and the remaining lattice can be completed, 29} 30 visited [a] [B] = 0; 31 flag --; // return 32 false; // you cannot finish all the grids, 33} 34 35 int main () 36 {37 scanf ("% D", & n); 38 int I, j, k = 1; 39 while (n --) {40 printf ("Scenario # % d: \ n ", k ++); 41 scanf ("% d", & q, & p); 42 flag = 0; 43 memset (visited, 0, sizeof (visited )); 44 int solved = 0; 45 for (I = 1; I <= p; I ++) {46 for (j = 1; j <= q; j ++) {// traverse all possible starting points 47 if (dfs (I, j) {48 solved = 1; 49 for (int l = 0; l <p * q; l ++) 50 printf ("% c % d", ans1 [l], ans2 [l]); 51 printf ("\ n"); 52 break; 53} 54} 55} 56 if (! Solved) 57 printf ("impossible \ n"); 58} 59 return 0; 60}