哈理工oj-1440-残缺的棋盘【BFS】

题目链接:点击打开链接

1440: 残缺的棋盘

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 196   Solved: 55
[ Submit][ Status][ Web Board]

Description

 在国际象棋里,王是最重要的一个棋子。每一步,王可以往上下左右或者对角线方向移动一步,如下图所示。

 

给定两个格子A(r1,c1), B(r2,c2),你的任务是计算出一个王从AB至少需要走多少步。为了避免题目太简单,我们从棋盘里拿掉了一个格子C(r3,c3)ABC保证互不相同),要求王从A走到B的过程中不能进入格子C。在本题中,各行从上到下编号为1~8,各列从左到右编号为1~8

 

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<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int r1,r2,r3,c1,c2,c3;
int dx[]={-1,0,1,0,-1,-1,1,1};
int dy[]={0,-1,0,1,-1,1,-1,1};
bool vis[10][10];
int ans;
struct node
{
	int x,y,step;
};
bool judge(int a,int b)
{
	if(a<1||b<1||a>8||b>8||vis[a][b])
		return 0;
	return 1;
}
int bfs(int a,int b)
{
	node now,next;
	now.x=a; now.y=b; now.step=0;
	vis[a][b]=1;
	vis[r3][c3]=1;
	queue<node> Q;
	while(!Q.empty())	Q.pop();
	Q.push(now);
	while(!Q.empty())
	{
		now=Q.front();
		Q.pop();
		if(now.x==r2&&now.y==c2)
			return now.step;
		/*
		if(now.x==r2&&now.y==c2)
		{
			printf("%d\n",now.step);
			return ;
		}
		*/
		for(int i=0;i<8;i++)
		{
			next.x=now.x+dx[i];
			next.y=now.y+dy[i];
			if(judge(next.x,next.y))
			{
				vis[next.x][next.y]=1;
				next.step=now.step+1;
				Q.push(next);
			}
		}
	}
}
int main()
{
	int text=0;
	while(~scanf("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3))
	{
		memset(vis,0,sizeof(vis));
		printf("Case %d: %d\n",++text,bfs(r1,c1));
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值