题目大意:
给出一个国际棋盘的大小,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。
思路:
dfs即可,难点在于题目要求以字典序输出,所以对于搜索的顺序有要求
dx[] = { -1, 1, -2, 2, -2, 2, -1, 1 };
dy[] = { -2, -2, -1, -1, 1, 1, 2, 2 };
/*dfs 骑士环游问题 */ #include <iostream> #include <cstdio> #include <cstring> using namespace std; bool b[30][30], flag; int dx[] = { -1, 1, -2, 2, -2, 2, -1, 1 },dy[] = { -2, -2, -1, -1, 1, 1, 2, 2 }; int n, m, end; char ch[60]; bool isfoot(int x, int y) { return (x>= 0 && x< n && y>= 0 && y< m); } void dfs(int x, int y, int count, char *ch) { if(flag) return; if(count == end) { puts(ch); flag = true; return; } for(int i = 0; i< 8; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if(isfoot(xx, yy) && !b[xx][yy]) { b[xx][yy] = true; ch[count] = yy + 'A'; ch[count+1] = xx + '1'; dfs(xx, yy, count+2, ch); b[xx][yy] = false; } } } void slove() { scanf("%d%d", &n, &m); end = n*m*2; flag = false; for(int i = 0; i< m; i++) { if(flag) break; for(int j = 0; j< n; j++) { memset(ch, 0, sizeof(ch)); memset(b, 0, sizeof(b)); ch[0] = i + 'A'; ch[1] = j + '1'; b[j][i] = true; dfs(j, i, 2, ch); if(flag) break; } } if(!flag) printf("impossible "); printf(" "); } int main() { int n; scanf("%d", &n); for(int i = 1; i<= n; i++) { printf("Scenario #%d: ", i); slove(); } return 0; }