zoj 1091 直接ac

本文提供了一种解决骑士在国际象棋棋盘上从一个位置到另一个位置所需最少步数的方法,通过广度优先搜索(BFS)算法实现。

转自  http://blog.youkuaiyun.com/wmbol/article/details/5546903 

/* * 1091.cpp * * Created on: Apr 29, 2010 * Author: wyy * */ #include<cstdio> #include<queue> using namespace std; struct point { int x, y, num; }; int dx[8] = {1, 1, -1, -1, 2, -2, 2, -2}; int dy[8] = {2, -2, 2, -2, 1, 1, -1, -1}; bool visited[8][8]; point p1, p2; char str1[3], str2[3]; void Init() { for(int i = 0; i < 8; ++i) for(int j = 0; j < 8; ++j) visited[i][j] = false; p1.x = str1[0] - 'a'; p2.x = str2[0] - 'a'; p1.y = str1[1] - '1'; p2.y = str2[1] - '1'; p1.num = 0; visited[p1.x][p1.y] = true; } bool IsValid(point p) { return (p.x >= 0 && p.y >= 0 && p.x < 8 && p.y < 8); } void BFS() { queue<point> Q; point m, n; Q.push(p1); while(!Q.empty()) { m = Q.front(); if(m.x == p2.x && m.y == p2.y) { printf("To get from %s to %s takes %d knight moves.\n", str1, str2, m.num); break; } Q.pop(); for(int i = 0; i < 8; ++i) { n.x = m.x + dx[i]; n.y = m.y + dy[i]; if(IsValid(n) && !visited[n.x][n.y]) { visited[n.x][n.y] = true; n.num = m.num + 1; Q.push(n); } } } } int main() { //freopen("input.txt", "r", stdin); while(scanf("%s%s", str1, str2) != EOF) { Init(); BFS(); } //fclose(stdin); return 0; }第2个#include <iostream> #include<stdio.h> #include<string.h> #include<stdlib.h> using namespace std; int knight[8][8];//棋盘 int x[]={1,1,2,2,-1,-1,-2,-2}; int y[]={2,-2,1,-1,2,-2,1,-1}; void dfs(int si,int sj,int moves) { //边界控制 if(si<0||sj<0||si>=8||sj>=8||moves>=knight[si][sj]) return ; knight[si][sj] = moves;//最优解 //分别向8个方向搜索 for(int i=0;i<8;i++) { dfs(si+x[i],sj+y[i],moves+1); } } int main() { char s[20]; char a[10],b[10]; while(gets(s)) { if(strlen(s)==0) break; sscanf(s,"%s%s",a,b); memset(knight,0,sizeof(int)); dfs(a[0]-'a',a[1]-'1',0); } printf("To get from %s to %s takes %d knight moves.\n",a,b,knight[b[0]-'a'][b[1]-'1']); return 0; }



转载于:https://www.cnblogs.com/dbstone/archive/2011/10/08/2404783.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值