题意:一只棋盘上的马,从一个点到另外一个点要走多少步

解法:广搜

#include<stdio.h>
#include<iostream>
#include <strstream>
#include<string>
#include<memory.h>
#include<math.h>
#include<sstream>
using namespace std;
const int MAXR = 8;
const int MAXC = 'h' - 'a' + 1;
struct Node
{
int r;
int c;
int total;
};
const Node dir[] = { { -1, 2 }, { 1, 2 }, { -2, 1 }, { 2, 1 }, { -2, -1 }, { 2,
-1 }, { -1, -2 }, { 1, -2 } };
struct Queue
{
Node a[MAXR * MAXC];
int total;
int position;
Queue()
{
total = 0;
position = 0;
}
;
Node offerNode()
{
Node node = a[position++];
return node;
}
void pushNode(Node node)
{
a[total++] = node;
}
bool empty()
{
return position == total;
}
};
int bfs(Queue queue, Node e, int used[][MAXC + 1])
{
Node t;
while (!queue.empty())
{
t = queue.offerNode();
if (t.c == e.c && t.r == e.r)
{
return t.total;
}
int nt = t.total + 1;
for (int i = 0; i < 8; i++)
{
int er = t.r + dir[i].r;
int ec = t.c + dir[i].c;
if (er < 1 || ec < 1 || er > MAXR || ec > MAXC || used[er][ec] == 1)
{
continue;
}
Node node;
node.c = ec;
node.r = er;
node.total = nt;
queue.pushNode(node);
used[er][ec] = 1;
}
}
return 0;
}
int main()
{
//freopen("d:\\1.txt", "r", stdin);
char sc, sr;
char ec, er;
while (cin >> sc >> sr >> ec >> er)
{
int total = 0;
if (sc == ec && sr == er)
{
cout << "To get from " << sc << sr << " to " << ec << er
<< " takes " << total << " knight moves." << endl;
continue;
}
Queue queue;
Node s, e;
s.r = sr - '0';
s.c = sc - 'a' + 1;
e.r = er - '0';
e.c = ec - 'a' + 1;
s.total = 0;
queue.pushNode(s);
int used[MAXR + 1][MAXC + 1];
memset(used, 0, sizeof(used));
used[s.r][s.c] = 1;
total = bfs(queue, e, used);
cout << "To get from " << sc << sr << " to " << ec << er << " takes "
<< total << " knight moves." << endl;
}
}

  

最新文章

  1. 使用CSDN Code将网站部署到Windows Azure Website上
  2. 前端神器avalonJS入门(二)
  3. FileUploadInterceptor拦截器的笔记
  4. 分享一个基于EF5.0封装的BaseDAL
  5. Oracle EM 不能访问
  6. sql常识- UNIQUE
  7. 三、T4模板与实体生成
  8. (转)Android创建桌面快捷方式两种方法
  9. Meta http-equiv属性详解
  10. Java并发框架——公平性
  11. for循环和foreach循环遍历集合的效率比较
  12. (52)Wangdao.com第七天_字面量/变量_标识符_数据类型_数据的存储
  13. virtualbox下centos虚拟机安装增强工具教程和常见错误解决
  14. JMeter学习(一)工具简单介绍(转载)
  15. 时间处理:计算下一天日期,如输入&quot;2004/12/31&quot;(注释2014年12月31日),则输出&quot;2005/1/1&quot;.
  16. Seaching TreeVIew WPF
  17. Antlr4 SQL Query 解析实例
  18. linux下的pd
  19. django入门-自定义管理界面-part7
  20. RabbitMQ---2、介绍

热门文章

  1. liunx服务程序的安装及配置
  2. MyEclipse 2014 破解图文详细教程
  3. HPU 1471:又是斐波那契数列??(大数取模)
  4. WebSocket(二)-WebSocket、Socket、TCP、HTTP区别
  5. 彻底删除vscode及安装的插件和个人配置信息
  6. error MSB3073: 命令“regsvr32 /s /c:VCEnd”已退出,代码为 3
  7. SOALog
  8. Python之包管理工具:distutils、setuptools、distribute、setup.py、easy_install、easy_install、pip
  9. hdu3037——卢卡斯定理
  10. OpenWrt在没有Luci时刷机