CSU - 1511(BFS)

题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1511

1511: 残缺的棋盘

Submit Page     Summary     Time Limit: 1 Sec     Memory Limit: 128 Mb     Submitted: 1974     Solved: 683    

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

AC代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <queue>
using namespace std;
int dx[8]={0,0,1,-1,1,1,-1,-1};
int dy[8]={1,-1,0,0,1,-1,1,-1};
int vis[10][10],r1, c1, r2, c2, r3, c3,t;
struct node
{
    int x,y,step;
};
int bfs()
{
    memset(vis,0,sizeof(vis));
    node b,now,next;
    b.x=r1; b.y=c1; b.step=0;
    queue <node> q;
    while(!q.empty())q.pop();
    q.push(b);
    vis[b.x][b.y]=1;
    vis[r3][c3]=1;
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        if(now.x == r2 && now.y == c2)
            return now.step;
        for(int d=0;d<8;d++)
        {
            next = now;
            next.x += dx[d];
            next.y += dy[d];
            if(next.x<=0 || next.x>8 || next.y<=0 || next.y>8)continue;
            if(next.x == r3 && next.y == c3)continue;
            if(vis[next.x][next.y] == 1)continue;
            next.step++;
            if(next.x == r2 && next.y == c2)return next.step;
            vis[next.x][next.y]=1;
            q.push(next);
        }
    }
}

int main()
{
//    freopen("in.txt","r",stdin);
    t=1;
    while(scanf("%d %d %d %d %d %d",&r1, &c1, &r2, &c2, &r3, &c3)!=EOF)
    {
        printf("Case %d: %d\n",t,bfs());
        t++;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WQN20172674/article/details/82021545