您的位置:首页 > 编程语言 > C语言/C++

poj 2243:Knight Moves

2014-06-21 14:25 218 查看
解题思路:

最短路径,BFS

#include<iostream>
#include<cstring>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

int map[15][15];
int s1,s2;
int t1,t2;
bool visit [15][15];

int cover()
{
memset(map,0,sizeof(map));
map[s1+1][s2+1] = 1;
int step = 0;
while(map[t1+1][t2+1]==0)
{
for(int i=0;i<15;i++)
for(int j=0;j<15;j++)
visit[i][j] = false;
for(int i=2;i<=9;i++)
for(int j=2;j<=9;j++)
{
if(map[i][j]==0)
{
if(map[i-1][j-2]>0 && visit[i-1][j-2]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i-1][j+2]>0 && visit[i-1][j+2]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i+1][j-2]>0 && visit[i+1][j-2]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i+1][j+2]>0 && visit[i+1][j+2]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i-2][j-1]>0 && visit[i-2][j-1]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i-2][j+1]>0 && visit[i-2][j+1]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i+2][j-1]>0 && visit[i+2][j-1]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
if(map[i+2][j+1]>0 && visit[i+2][j+1]==false)
{
map[i][j] = 1;
visit[i][j] = true;
}
}
}
step++;
}
return step;
}

int main()
{
char c1,c2,c3,c4;
while(cin>>c1>>c2>>c3>>c4)
{
s1 = c1 - 'a' + 1;
s2 = c2 - '0';
t1 = c3 - 'a' + 1;
t2 = c4 - '0';
cout<<"To get from "<<c1<<c2<<" to "<<c3<<c4<<" takes "<<cover()<<" knight moves."<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ poj 最短路径