Knight Moves

BFS

题意:给你棋盘上两点的坐标,按照中国象棋中马的走法,求出其最短的步数。

// File Name: 1073.cpp
// Author: bo_jwolf
// Created Time: 2014年02月03日 星期一 21时24分46秒

#include<vector>
#include<list>
#include<map>
#include<set>
#include<deque>
#include<stack>
#include<bitset>
#include<algorithm>
#include<functional>
#include<numeric>
#include<utility>
#include<sstream>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<queue>

using namespace std;
int dir[ 15 ][ 5 ] = { { -2, 1 }, { -1, 2 }, { -2, -1 }, { -1, -2 },{ 2, 1 },{ 1, 2 }, { 2, -1 }, { 1, -2 } };
const int maxn = 1005;
int vis[ maxn ][ maxn ], sx, sy, ex, ey, Step = 0;
struct node{
	int x, y, step;
}edge[ maxn ];

void Bfs(){
	queue< node > Q;
	node temp, p, q;
	temp.x = sx;
	temp.y = sy;
	vis[ sx ][ sy ] = 1;
	temp.step = 0;
	Q.push( temp );
	if( sx == ex && sy == ey ){
		Step = 0;
		return;
	}
	while( !Q.empty() ){
		p = Q.front();
		Q.pop();
		for( int i = 0; i < 8; ++i ){
			int y = p.y + dir[ i ][ 0 ];
			int x = p.x + dir[ i ][ 1 ];
			if( x >= 0 && y >= 0 && x < 8 && y < 8 && !vis[ x ][ y ] ){
				q.x = x;
				q.y = y;
				q.step = p.step + 1;
				if( x == ex && y == ey ){
					Step = q.step;
					return;
				}
				vis[ x ][ y ] = 1;
				Q.push( q );
			}
		}
	}
}

int main(){
	char str1[ maxn ], str2[ maxn ];
	while( scanf( "%s %s", str1, str2 ) == 2 ){
		sx = str1[ 0 ] - 'a';
		sy = str1[ 1 ] - '1';
		ex = str2[ 0 ] - 'a';
		ey = str2[ 1 ] - '1';
		memset( vis, 0, sizeof( vis ) );
		Bfs();
		printf( "To get from %s to %s takes %d knight moves.\n", str1, str2, Step );
	}
return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值