广搜题,主要是理解题意:
棋盘上的路径都有颜色,起始时给定 3 个棋子的位置,按要求移动棋子,是否能将 3 个棋子移到同一位置。如果可以,输出移动的最少步数,否则输出"impossible"。(移动要求:每次只能移动一个棋子,每个棋子只能沿着这样一条路径移动,这条路径和另外两个棋子之间的路径颜色相同。)
#include <iostream>
#include <queue>
using namespace std;
const int MAXN = 55;
int n; //棋盘中位置的数量
char mp[MAXN][MAXN]; //各位置之间的路线颜色
bool vis[MAXN][MAXN][MAXN]; //访问情况
struct status //棋盘状态
{
int loc[3]; //三个棋子的位置
int step; //移动次数
}start;
//广搜
void BFS()
{
start.step = 0;
vis[start.loc[0]][start.loc[1]][start.loc[2]] = true;
queue<status> q;
q.push(start);
while (!q.empty())
{
status temp = q.front();
q.pop();
for (int i = 0; i < 3; i++) //依次搜索3个棋子
{
for (int j = 1; j <= n; j++) //对每个棋子搜索各个移动位置
{
status next = temp;
//另外两个棋子的编号
int num1 = (i + 1) % 3;
int num2 = (i + 2) % 3;
//如果棋子i和位置j之间的路径颜色 等于 另外两个棋子之间的路径颜色
if (mp[next.loc[i]][j] == mp[next.loc[num1]][next.loc[num2]])
{
next.loc[i] = j; //棋子i移动到位置j
if (!vis[next.loc[0]][next.loc[1]][next.loc[2]])
{
vis[next.loc[0]][next.loc[1]][next.loc[2]] = true;
next.step++;
q.push(next);
if (next.loc[0] == next.loc[1] && next.loc[1] == next.loc[2])
{
cout << next.step << endl;
return;
}
}
}
}
}
}
cout << "impossible" << endl;
}
int main()
{
while (cin >> n)
{
if (n == 0)
break;
memset(vis, 0, sizeof(vis));
cin >> start.loc[0] >> start.loc[1] >> start.loc[2];
for (int i = 1; i <= n; i++) //输入各路径颜色
{
for (int j = 1; j <= n; j++)
cin >> mp[i][j];
}
if (start.loc[0] == start.loc[1] && start.loc[1] == start.loc[2])
cout << 0 << endl;
else
BFS();
}
return 0;
}
继续加油。