这个题意还是能理解就是不会各种搜索遍历
这些日子写写DFS BFS 基础题
这个先是看别人的思路, 自己写, 再看别人代码, 然后各种改才A掉的
基本照抄了。
#include <iostream>
#include <cstdlib>
using namespace std;
bool visited[10][10];
char path[100], success;
//可走的路径
int dx[8] = {-2, -2, -1, -1, +1, +1, +2, +2};
int dy[8] = {-1, +1, -2, +2, -2, +2, -1, +1};
int p, q;
//深搜
void DFS(int depth, int x, int y)
{
//判断是深度是否满足整个棋盘大小
visited[x][y] = true;
if (depth == p * q)
{
//输出数据
for (int i = 0; i < 2 * depth; i++)
printf("%c", path[i]);
printf("\n\n");
success = true;
return ;
}
//如果成功走出一条路线就退出搜索
for (int i = 0; i < 8 && success == false; i++)
{
int new_x = x + dx[i];
int new_y = y + dy[i];
//判断是否越界 并且 未被访问过
if (new_x >= 1 && new_x <= q && new_y >= 1 && new_y <= p && visited[new_x][new_y] == false)
{
path[2 * depth] = 'A' + new_x - 1;
path[2 * depth + 1] = '0' + new_y;
visited[new_x][new_y] = true;
DFS(depth+1, new_x, new_y);
visited[new_x][new_y] = false;
}
}
}
int main()
{
int T, k;
scanf("%d", &T);
k = 0;
while (k != T)
{
scanf("%d %d", &p, &q);
memset(visited, false, sizeof(visited));
//初始化起始位置
path[0] = 'A'; path[1] = '1';
success = false;
printf("Scenario #%d:\n", ++k);
DFS(1, 1, 1);
if (success == false)
printf("impossible\n\n");
}
return 0;
}