博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UVa 439 - Knight Moves 搜索专题
阅读量:4074 次
发布时间:2019-05-25

本文共 1380 字,大约阅读时间需要 4 分钟。

FILE 13381
56.27%
5157
93.21%
题目链接:

题目类型: 搜索

样例输入:

e2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6

样例输出:

To get from e2 to e4 takes 2 knight moves.To get from a1 to b2 takes 4 knight moves.To get from b2 to c3 takes 2 knight moves.To get from a1 to h8 takes 6 knight moves.To get from a1 to h7 takes 5 knight moves.To get from h8 to a1 takes 6 knight moves.To get from b1 to c3 takes 1 knight moves.To get from f6 to f6 takes 0 knight moves.

分析:

这题也是一道十分经典的搜索入门题。  由于题目是指定象棋中马的开始位置,与目标位置, 要求马以最少的步数走到目标位置。 凡是求最短步数的,一般用BFS做比较好。

求步数时, 有个小技巧, 开个vis数组,初始化为0, 然后这个用来记录走的步数,而不仅仅是用来标记是否走过。具体见代码

#include
#include
#include
using namespace std;char start[3], end[3];int dir[8][2] = {
{-2,1},{-1,2},{1,2},{2,1}, {2,-1},{1,-2},{-1,-2},{-2,-1}};int vis[10][10]; struct Node{int x, y; };Node que[1000];void bfs(){ int front=0, rear=1; que[0].x=start[0]-'a', que[0].y=start[1]-'0'-1; vis[que[0].x][que[0].y] = 1; while(front
=0 && dx<8 && dy>=0 && dy<8 && !vis[dx][dy]){ vis[dx][dy] = vis[t.x][t.y]+1; // 记住步数 Node temp; temp.x=dx, temp.y=dy; que[rear++] = temp; } } }}int main(){#ifdef LOCAL freopen("input.txt", "r", stdin);#endif while(~scanf("%s %s", start, end) && start[0]){ memset(vis, 0, sizeof(vis)); bfs(); } return 0;}

转载地址:http://kyzni.baihongyu.com/

你可能感兴趣的文章
字节跳动后端开发一面
查看>>
CentOS Tensorflow 基础环境配置
查看>>
centOS7安装FTP
查看>>
FTP的命令
查看>>
CentOS操作系统下安装yum的方法
查看>>
ping 报name or service not known
查看>>
FTP 常见问题
查看>>
zookeeper单机集群安装
查看>>
do_generic_file_read()函数
查看>>
Python学习笔记之数据类型
查看>>
Python学习笔记之特点
查看>>
shell 快捷键
查看>>
VIM滚屏操作
查看>>
EMC 2014存储布局及十大新技术要点
查看>>
linux内核内存管理(zone_dma zone_normal zone_highmem)
查看>>
将file文件内容转成字符串
查看>>
循环队列---数据结构和算法
查看>>
优先级队列-数据结构和算法
查看>>
链接点--数据结构和算法
查看>>
servlet中请求转发(forword)与重定向(sendredirect)的区别
查看>>