您的位置:首页 > 其它

ZOJ 1091 Knight Moves

2015-06-15 15:34 363 查看
#include <iostream>
#include <stdio.h>
#include <string>
#include <queue>
using namespace std;
int c[9][9];//存放每个位置
int dir[8][2] = { { -2, -1 }, { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 }, { -1, -2 } };
st\
ruct node
{
int x, y, count;//xy代表行列数 count代表步数
};
node start, finish;//定义结点分别代表骑士起始位置和终止位置
int bfs()
{
memset(c, 0, sizeof(c));//数组c内元素全初始化为0
node pre, cur;//定义结点分别代表骑士上个位置和当前的位置
start.count = 0;////起始位置走过的步数为0
queue<node> q;//定义一个路径容器适配器
q.push(start);//把起点放进去
c[start.x][start.y] = 1;//起点设置为1
while (!q.empty())//当适配器未被完全清空时
{
pre = q.front();//起点节点赋给上个位置节点
q.pop();//删除赋值后的节点
if (pre.x == finish.x&&pre.y == finish.y)//移动到终点之后
return pre.count;//返回值为步数
for (int i = 0; i < 8; i++)//循环调用8个方向
{
cur.x = pre.x + dir[i][0];
cur.y = pre.y + dir[i][1];//计算当前位置
if (cur.x<1 || cur.x>8 || cur.y<1 || cur.y>8)continue;//行列数溢出 执行下次循环
if (c[cur.x][cur.y] == 1)continue;//当前位置为1 执行下次循环
c[cur.x][cur.y] = 1;//把当前位置赋为1
cur.count = pre.count + 1;//当前步数比上个位置多一步
q.push(cur);//把当前节点放入适配器
}//一个for循环结束 八个方向算完 适配器增加了若干解点
}//不断重复循环 计算步数
return -1;
}
int main()
{
char row, endr;
int col, endc;
int min;
while (cin >> row)
{
cin >> col;
cin >> endr >> endc;
start.x = row - 'a' + 1;
start.y = col;
finish.x = endr - 'a' + 1;
finish.y = endc;
if (start.x == finish.x&&start.y == finish.y) min = 0;
min = bfs();
printf("To get from %c%d to %c%d takes %d knight moves.\n", row, col, endr, endc, min);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm