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
题目分析:
这道题求得是起点A走到终点B的最小步数,可以用最短路径BFS来做。如果还没学的话,也可以直接进行位置判断。我们可以发现起点A和终点B的位置关系有以下几种:在同一列、在同一行、在对角线上、不在对角线上也不在同一行和同一列,然后阻拦点C就只需要知道在不在最小路径上(每一种位置关系的最小路径,画图就可以知道)。比如,起点A和终点B在同一列,那么最小路径就是沿着这一列走就可以了。然后在走的过程中有阻拦点的话,最小路径就可能加1,也有可能不加,自己画图判断)
代码如下:
# include<stdio.h>
# include<string.h>
# include<math.h>
# include<iostream>
using namespace std;
int main()
{
int r1,c1,r2,c2,r3,c3;
int k=1,num;
while(scanf("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3)!=EOF)
{
num=0;
if(r1==r2)
{
num=fabs(c1-c2);
/// if(r1==r3&&(c1<c2?c1:c2)<c3&&c3<(c1<c2?c2:c1) )注意:阻拦点C挡住不一定最小步数加1.
/// num++;
}
else if(c1==c2)
{
num=fabs(r1-r2);
/// if(c1==c3&&(r1<r2?r1:r2)<r3&&r3<(r1<r2?r2:r1)) 注意:阻拦点C挡住不一定最小步数加1
///num++;
}
else if(fabs(r1-r2)==fabs(c1-c2))
{
num=fabs(r1-r2);
if((fabs(r1-r3)==fabs(c1-c3))&&fabs(r2-r3)==fabs(c2-c3)&&(r1<r2?r1:r2)<r3&&r3<(r1<r2?r2:r1))
num++;
}
else
{
num=fabs(r1-r2);
if(num<fabs(c1-c2)) num=fabs(c1-c2);
}
printf("Case %d: %d\n",k++,num);
}
return 0;
}
以下是最小路径BFS的解法:
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
const int M=10;
int ti[M][M];
queue <int> re;
int dx[]={0,0,1,-1,1,1,-1,-1};
int dy[]={1,-1,0,0,1,-1,1,-1};
int bfs(int stx,int sty,int edx,int edy)
{
while(!re.empty())
re.pop();
re.push(stx+sty*M);
ti[stx][sty]=1;
while(!re.empty())
{
int t=re.front();
re.pop();
int tx=t%M,ty=t/M;
for(int i=0;i<8;i++)
{
int x=tx+dx[i],y=ty+dy[i];
if(ti[x][y])
continue;
if(x<=0||y<=0||x>8||y>8)
continue;
if(x==edx&&y==edy)
{
return ti[tx][ty];
}
ti[x][y]=ti[tx][ty]+1;
re.push(x+y*M);
}
}
}
int main()
{
int r1,c1,r2,c2,r3,c3;
int k=1;
while(scanf("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3)!=EOF)
{
memset(ti,0,sizeof(ti));
ti[r3][c3]=100;
printf("Case %d: %d\n",k++,bfs(r1,c1,r2,c2));
}
return 0;
}
总结;解决问题的方法不唯一,要学会举一反三。还有DFS和BFS是很重要的要认真学。