题目传送门
Description
“Hike on a Graph” is a game that is played on a board on which an undirected graph is drawn. The graph is complete and has all loops, i.e. for any two locations there is exactly one arrow between them. The arrows are coloured. There are three players, and each of them has a piece. At the beginning of the game, the three pieces are in fixed locations on the graph. In turn, the players may do a move. A move consists of moving one’s own piece along an arrow to a new location on the board. The following constraint is imposed on this: the piece may only be moved along arrows of the same colour as the arrow between the two opponents’ pieces.
In the sixties (“make love not war”) a one-person variant of the game emerged. In this variant one person moves all the three pieces, not necessarily one after the other, but of course only one at a time. Goal of this game is to get all pieces onto the same location, using as few moves as possible. Find out the smallest number of moves that is necessary to get all three pieces onto the same location, for a given board layout and starting positions.
Input Specification
The input file contains several test cases. Each test case starts with the number n. Input is terminated by n=0. Otherwise, 1<=n<=50. Then follow three integers p1, p2, p3 with 1<=pi<=n denoting the starting locations of the game pieces. The colours of the arrows are given next as a m×m matrix of whitespace-separated lower-case letters. The element mij denotes the colour of the arrow between the locations i and j. Since the graph is undirected, you can assume the matrix to be symmetrical.
Output Specification
For each test case output on a single line the minimum number of moves required to get all three pieces onto the same location, or the word “impossible” if that is not possible for the given board and starting locations.
Sample Input
3 1 2 3
r b r
b b b
r b r
2 1 2 2
y g
g y
0
Sample Output!
2
impossible
题目大意:
有一张图,上面的路径都是着色的,开始的时候有3个盘子在确定的点上,现在让你按要求沿图中的路径移动盘子(一步只能移动一只盘子),问是否能将3个盘子都移到同一个点上,如果可以,输出需要的最少步数,否则输出“impossible”。移动条件是:每个盘子只能沿着这样一条路移动,这条路的颜色和另外的两个盘子之间的路径上标记的颜色是一样的。
解题思路:
BFS入门题,比较直接的BFS题目,图为无向完全图,也就是n个点有n(n-1)/2条边,每两个点都有一条直通边,就是中间没有其他点,也可以理解为本身就是自己的最大团,这个条件也让题目更加方便简单;首先把三个盘子的每个点的位置想象成一个三维坐标(x,y,z),这样题目中说的三个盘子移动到一起,不就是判断移动到的位置是否满足(xy&&yz)这个关系吗?所以题目就简单化了,只要分别向x,y,z三个方向搜索(因为每次只能移动一步),每次搜索只需要判断盘子此时点的位置是否可以移动到邻接点位置(就是这条路的颜色和另外的两个盘子之间的路径上标记的颜色是否是一样的),可以的话就更新位置和该位置点的步数,再判断是否满足(xy&&yz)这个条件即可,不满足再执行上面的操作,最多循环到queue.empty()为true,就会出结果。
AC代码:
#include
#include
#include
#include
#include
#include
#include
#include
//#include