POJ - 1915 Knight Moves

1.题面

http://poj.org/problem?id=1915

2.解题思路

又是一道bfs搜索的题目,而且很基础,利用队列先进先出的性质实现bfs就好,然后ACM和PAT不一样的地方时,数据量会比较大,从前做PAT的时候,每组数据我都会使用新建立的队列,并且基本不做什么剪枝,但是ACM这样做会爆空间,正确的做法是每次都使用同一个队列,最好干脆不适用STL库中提供的队列,自己模拟就好。

3.解题代码

/*****************************************************************
    > File Name: tmp.cpp
    > Author: Uncle_Sugar
    > Mail: uncle_sugar@qq.com
    > Created Time: 2016年02月18日 星期四 15时07分56秒
 ****************************************************************/
# include <cstdio>
# include <cstring>
# include <cmath>
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <set>
# include <map>
# include <vector>
# include <stack>
using namespace std;


const int debug = 0;
const int size  = 300 + 10;
typedef long long ll;
struct coord{
	int x,y,step;
	coord(){}
	coord(int _x,int _y,int _step):x(_x),y(_y),step(_step){}
};
int dx[8] = {1,2,-1,-2,1,2,-1,-2};
int dy[8] = {2,1,-2,-1,-2,-1,2,1};
int g[size][size];

coord queue[size*size];
int s_que=0,e_que=0;


int n;
bool inrange(int tx,int ty){
	return tx<n&&tx>=0&&ty<n&&ty>=0;
}
int main()
{
	std::ios::sync_with_stdio(false);cin.tie(0);
	int i,j,k;
	int T;
	cin >> T;
	while (T--){
		cin >> n;
		memset(g,0,sizeof(g));
		s_que = e_que = 0;
		int sx,sy;
		int ex,ey;
		cin >> sx >> sy;
		cin >> ex >> ey;
		g[sx][sy] = 1;
		queue[e_que] = coord(sx,sy,0);e_que++;
		int ans = 0;
		while (g[ex][ey]==0&&s_que<e_que){
			coord T = queue[s_que];s_que++;if (debug) cout << "gets "<< T.x << ' ' << T.y << endl;
			for (i=0;i<8;i++){
				int tx = T.x + dx[i];
				int ty = T.y + dy[i];if (debug) cout << "gets tx ty "<< tx << ' ' << ty << endl;
				int tstep = T.step + 1;
				if (tx==ex&&ty==ey){
					g[tx][ty] = 1;ans = tstep;
					break;
				}if (debug) cout  << "range " << inrange(tx,ty) << ' ' << g[tx][ty] << endl;
				if (inrange(tx,ty)&&g[tx][ty]==0){
                    g[tx][ty] = 1;
					queue[e_que] = coord(tx,ty,tstep);e_que++;
				}
			}
			if (g[ex][ey]==1)
				break;
		}
		if (g[ex][ey]==1)
			cout << ans << '\n';
		else
			cout << "error!" << endl;
	}
	return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值