广搜 象棋格
来源:互联网 发布:国家顶级域名us 编辑:程序博客网 时间:2024/04/30 21:13
在一张8*8的象棋盘上,马走日的方式移动,问任意给定的两点pa,pb,问从pa到pb至少需要移动几步。
用 BFS,本题中字符串常量的输入,声明用到了C++中的string类!下为打印样式:
Source:POJ2243
Type:BFS
#include <iostream>#include <cstring>#include <cstdlib>#include <string>#include <cstdio>#include <queue>#include <stack>#include <algorithm>using namespace std;int dx[] = { 1, 2, 2, 1, -1, -2, -2, -1};int dy[] = { 2, 1, -1, -2, -2, -1, 1, 2};int step[8][8], fa[8][8];//本题没有对路径的要求,加上父亲节点只是为了方便调试bool vis[8][8];inline bool inbound(int x, int y){ return(x>=0&&x<8&&y>=0&&y<8);}inline int encode(int x, int y) { return x * 8 + y; }inline int newPos(int old, int method){ int x = old / 8, y = old % 8; x += dx[method], y += dy[method]; if (inbound(x, y) )return encode(x, y); else return -1;}inline int getx(string s) { return int(s[0] - 'a'); }inline int gety(string s) { return int(s[1] - '1'); }int bfs(string _beg, string _tar){ int beg = encode(getx(_beg), gety(_beg)); int tar = encode(getx(_tar), gety(_tar)); memset(step, 0, sizeof(step)); memset(vis, 0, sizeof(vis)); memset(fa, 0, sizeof(fa)); queue<int> q; q.push(beg); vis[beg / 8][beg % 8] = 1; fa[beg / 8][beg % 8] = beg; while (!q.empty()) { int top = q.front(); q.pop(); if (top == tar) break;//跳出循环后,由于step[][]数组被初始化,所以直接是0. for (int j = 0; j < 8; j++) { int tmp = newPos(top, j); if (tmp != -1 && inbound(tmp/8,tmp%8) && !vis[tmp / 8][tmp % 8]) { vis[tmp / 8][tmp % 8] = 1; step[tmp / 8][tmp % 8] = step[top / 8][top % 8] + 1; fa[tmp / 8][tmp % 8] = top; q.push(tmp); } } } return step[tar / 8][tar % 8];}int main(){ string b, t; while (cin >> b >> t) printf("To get from %s to %s takes %d knight moves.\n", b.c_str(), t.c_str(), bfs(b, t)); return 0;}
0 0
- 广搜 象棋格
- HDU--杭电--1372--Knight Moves--广搜--就是象棋里面‘马’走日一样走,水题
- 象棋
- 象棋
- 象棋
- 象棋
- 广搜
- 广搜
- 广搜
- 广搜
- 广搜
- 广搜
- POJ_3278_广搜
- 深搜 广搜
- hdu 1026 广搜
- 1242 rescue 广搜
- zoj 1091 广搜。
- POJ3083 广搜&模拟
- 黑马程序员——多线程
- 暑期大作战第四天
- searchcode 代码搜索引擎及使用
- 设计模式之MVC模式
- 实现RTP协议的H.264视频传输系统
- 广搜 象棋格
- 数学之路-python计算实战(14)-机器视觉-图像增强(直方图均衡化)
- 【2-sat】uva1391
- 页面标签语义化
- 来帝都的时间
- java编程之--当类的访问器邂逅可变对象成员时
- C语言---基础概念和常识
- 一个小小的笔顺程序,按钮太多,暂时实现了两个
- 定期整理博客