1330:【例8.3】最少步数
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 4745 通过数: 2459
【题目描述】
在各种棋中,棋子的走法总是一定的,如中国象棋中马走“日”。有一位小学生就想如果马能有两种走法将增加其趣味性,因此,他规定马既能按“日”走,也能如象一样走“田”字。他的同桌平时喜欢下围棋,知道这件事后觉得很有趣,就想试一试,在一个(100×100)的围棋盘上任选两点A、B,A点放上黑子,B点放上白子,代表两匹马。棋子可以按“日”字走,也可以按“田”字走,俩人一个走黑马,一个走白马。谁用最少的步数走到左上角坐标为(1,1)的点时,谁获胜。现在他请你帮忙,给你A、B两点的坐标,想知道两个位置到(1,1)点可能的最少步数。
【输入】
A、B两点的坐标。
【输出】
最少步数。
【输入样例】
12 16
18 10
【输出样例】
8
9
# include<iostream>
# include<cstring>
# include<queue>
using namespace std;
typedef pair<int ,int> point;
int dr[]={1,1,-1,-1,2,2,-2,-2,2,2,-2,-2};
int dc[]={2,-2,2,-2,1,-1,1,-1,2,-2,2,-2};
bool vis[100][100];
int d[101][101];
void bfs(point s)
{
memset(vis,0,sizeof(vis));
d[s.first][s.second]=0;
queue<point> q;
q.push(s);
vis[s.first][s.second]=true;
while(!q.empty())
{
point k=q.front();
q.pop();
if(k.first==1&&k.second==1) {
cout<<d[1][1]<<endl;
break;
}
for(int i=0;i<12;i++)
{
int newr=k.first+dr[i];
int newc=k.second+dc[i];
if(newr>=1&&newr<=100&&newc>=1&&newc<=100)
{
if(!vis[newr][newc])
{
d[newr][newc]=d[k.first][k.second]+1;
q.push((point){newr,newc});
vis[newr][newc]=true;
}
}
}
}
}
int main()
{
point a,b;
cin>>a.first>>a.second;
cin>>b.first>>b.second;
bfs(a);
bfs(b);
return 0;
}