1511: 残缺的棋盘
Description
Input
输入包含不超过10000 组数据。每组数据包含6个整数r1, c1, r2, c2, r3, c3 (1<=r1, c1, r2, c2, r3, c3<=8). 三个格子A, B, C保证各不相同。
Output
对于每组数据,输出测试点编号和最少步数。
Sample Input
1 1 8 7 5 6
1 1 3 3 2 2
Sample Output
Case 1: 7
Case 2: 3
宽度优先搜索,注意边界即可。
代码如下:
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int INF = 1000000;
typedef pair<int,int> P;
int ans;
int dir[8][2] = {{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
int d[9][9];
int sx,sy,ex,ey,cx,cy;
int bfs()
{
queue <P> que;
for(int i = 1;i < 9;i++){
for(int j = 1;j < 9;j++){
d[i][j] = INF;
}
}
que.push(P(sx,sy));
d[sx][sy] = 0;
while(que.size()){
P p = que.front();
que.pop();
if(p.first == ex && p.second == ey)
break;
for(int i = 0;i < 8;i++){
int nx = p.first + dir[i][0];
int ny = p.second + dir[i][1];
if(nx < 1 || 9 <= nx || ny < 1 || 9 <= ny || (nx == cx && ny == cy) || d[nx][ny] != INF){
continue;
}else{
que.push(P(nx,ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}
return d[ex][ey];
}
int main()
{
int ncase,i,j,k;
while(scanf("%d %d %d %d %d %d",&sx,&sy,&ex,&ey,&cx,&cy) != EOF){
ans = bfs();
printf("Case %d: %d\n",++ncase,ans);
}
return 0;
}