CSU 1511 残缺的棋盘

Problem I: 残缺的棋盘

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 526   Solved: 186
[ Submit][ Status][ Web Board]

Description

CSU 1511 残缺的棋盘_第1张图片

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


简单BFS搜索。判断条件里加上r3,c3就行了。

#include <stdio.h>
#include <queue>
#include <string.h>
#define N 8
using namespace std;
typedef struct node{
    int position, step;
}node;
queue<node> q;
int r1, c1, r2, c2, r3, c3;
int dx[8] = { 0, 1, 1, -1, -1, 0, -1, 1 };
int dy[8] = { 1, 1, 0, 1, 0, -1, -1, -1 };
int vis[N][N];
int kstart,kend;
int bfs(int pos)
{
    while (!q.empty())
        q.pop();
    node now, next;
    now.position = pos;
    now.step = 0;
    vis[now.position / N][now.position%N] = 1;
    q.push(now);
    while (!q.empty())
    {
        node front = q.front();
        q.pop();
        if (((front.position) / N) == (kend/N) && ((front.position) % N) == kend%N)
        {
            return front.step;
        }
        int x = front.position / N;
        int y = front.position%N;
        for (int i = 0; i < 8; i++)
        {
            int xx = x + dx[i];
            int yy = y + dy[i];
            next.position = xx*N + yy;
            if (xx < 0 || yy < 0 || xx >= N || yy >= N || vis[xx][yy] == 1||(xx==r3&&yy==c3))
                continue;
            vis[xx][yy] = 1;
            next.step = front.step + 1;
            q.push(next);
        }
    }
    return -1;
}
int main()
{
    int i=1;
    while(scanf("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3)>0)
    {
        memset(vis,0,sizeof(vis));
        r1--,c1--,r2--,c2--,r3--,c3--;
        kstart=r1*N+c1;
        kend=r2*N+c2;
        int ans=bfs(kstart);
        printf("Case %d: %d\n",i++,ans);
    }
    return 0;
}
 
/**************************************************************
    Problem: 1511
    User: lizhaowei213
    Language: C++
    Result: Accepted
    Time:120 ms
    Memory:1064 kb
****************************************************************/


你可能感兴趣的:(CSU 1511 残缺的棋盘)