Knight's Journey(深搜+字典序)

本文探讨了骑士周游问题的解决方法,这是一种经典的棋盘遍历问题,要求骑士按照特定移动规则访问棋盘上的每一个格子恰好一次。文章提供了一个深度优先搜索(DFS)的实现方案,并附带了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Background 
The knight is getting bored of seeing the same black and white squares again and again and has decided to make a journey 
around the world. Whenever a knight moves, it is two squares in one direction and one square perpendicular to this. The world of a knight is the chessboard he is living on. Our knight lives on a chessboard that has a smaller area than a regular 8 * 8 board, but it is still rectangular. Can you help this adventurous knight to make travel plans? 

Problem 
Find a path such that the knight visits every square once. The knight can start and end on any square of the board.

Input

The input begins with a positive integer n in the first line. The following lines contain n test cases. Each test case consists of a single line with two positive integers p and q, such that 1 <= p * q <= 26. This represents a p * q chessboard, where p describes how many different square numbers 1, . . . , p exist, q describes how many different square letters exist. These are the first q letters of the Latin alphabet: A, . . .

Output

The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. Then print a single line containing the lexicographically first path that visits all squares of the chessboard with knight moves followed by an empty line. The path should be given on a single line by concatenating the names of the visited squares. Each square name consists of a capital letter followed by a number. 
If no such path exist, you should output impossible on a single line.

Sample Input

3
1 1
2 3
4 3

Sample Output

Scenario #1:
A1

Scenario #2:
impossible

Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4

 被字典序给坑了!!!

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int mp[26][26],vis[26][26],n,m,flag;
int tx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int ty[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
int cx[27];
char cy[27];
void dfs(int x,int y,int sum)
{
 if(sum==n*m)
 {
  for(int i=0;i<sum;i++)
    printf("%c%d",cy[i],cx[i]);
  printf("\n");
  flag=1;
  return ;
 }
 for(int i=0;i<8;i++)
 {
  int dx=x+tx[i];
  int dy=y+ty[i];
  if(dx>=0&&dx<n&&dy>=0&&dy<m)
        if(!vis[dx][dy])
         {
             vis[dx][dy]=1;
             cx[sum]=dx+1,cy[sum]=dy+'A';
             dfs(dx,dy,sum+1);
             if(flag) return ;
             vis[dx][dy]=0;
         }
 }
}

int main()
{
 int x,ans=1;
 scanf("%d",&x);
 while(x--)
 {
     memset(mp,0,sizeof(mp));
     memset(vis,0,sizeof(vis));
     vis[0][0]=1;
     flag=0;
     scanf("%d%d",&n,&m);
     cx[0]=1,cy[0]='A';
     printf("Scenario #%d:\n",ans);
     dfs(0,0,1);
     if(flag==0)printf("impossible\n");
     if(x!=0) printf("\n");
     ans++;
 }
 return 0;
}

 传送门:迷宫类型深搜(dfs,深度优先搜索)

转载于:https://www.cnblogs.com/wangtao971115/p/10358376.html

### C++ 实现 Knight Moves 算法 以下是基于广度优先(BFS) 的 C++ 实现方法来解决 Knight Moves 问题。该算法通过 BFS 遍历棋盘上的所有可能位置,直到找到目标位置为止。 #### 主要思路 骑士的移动方式类似于国际象棋中的马步,每次可以跳跃到最多 8 个不同的方向。为了计算从起点到终点所需的最小步数,可以通过 BFS 来遍历所有的可能性,并记录已经访问过的节点以避免重复计算[^1]。 下面是完整的代码实现: ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; int map[10][10]; char start_pos[3], end_pos[3]; struct Node { int x, y; int num; // 记录当前路径长度 }; // 定义骑士的八个移动方向 int directions[8][2] = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; void bfs(int sx, int sy, int ex, int ey) { queue<Node> q; Node t, p; // 初始化起始点 t.x = sx; t.y = sy; t.num = 0; // 将起始点标记为已访问 memset(map, 0, sizeof(map)); map[sx][sy] = 1; q.push(t); while (!q.empty()) { t = q.front(); q.pop(); // 如果到达目标点,则输出结果并返回 if (t.x == ex && t.y == ey) { printf("To get from %s to %s takes %d knight moves.\n", start_pos, end_pos, t.num); return; } // 遍历所有可能的方向 for (int i = 0; i < 8; ++i) { int nx = t.x + directions[i][0]; int ny = t.y + directions[i][1]; // 判断新位置是否合法且未被访问过 if (nx > 0 && nx < 9 && ny > 0 && ny < 9 && !map[nx][ny]) { p.x = nx; p.y = ny; p.num = t.num + 1; map[nx][ny] = 1; // 标记为已访问 q.push(p); } } } } int main() { while (scanf("%s%s", start_pos, end_pos) != EOF) { // 转换输入坐标为数值形式 int sx = start_pos[0] - 'a' + 1; int sy = start_pos[1] - '0'; int ex = end_pos[0] - 'a' + 1; int ey = end_pos[1] - '0'; bfs(sx, sy, ex, ey); } return 0; } ``` --- #### 关键点解析 1. **结构体定义** 使用 `Node` 结构体存储当前位置 `(x, y)` 和当前路径长度 `num`,便于在队列中传递信息[^1]。 2. **方向数组** 定义了一个二维数组 `directions` 表示骑士的所有可能移动方向。这简化了后续的逻辑处理[^1]。 3. **边界条件检查** 在扩展新的节点时,需确保其位于棋盘范围内 (`1 ≤ x, y ≤ 8`) 并且尚未被访问过。 4. **终止条件** 当 BFS 找到目标位置时立即停止,并打印所需步数[^1]。 5. **初始化重置** 每次调用 BFS 前都需要重新初始化 `map` 数组,用于标记哪些位置已经被访问过[^1]。 --- #### 输入输出说明 - **输入格式**: 多组测试数据,每组包含两个字符串表示起点和终点的位置。 - **输出格式**: 对于每组测试数据,按照指定格式输出从起点到终点所需的最少步数。 样例运行如下: ```plaintext e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6 ``` 对应输出为: ```plaintext To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves. ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值