现在的位置: 首页 > 综合 > 正文

hdu 1072 BFS

2013年10月17日 ⁄ 综合 ⁄ 共 1096字 ⁄ 字号 评论关闭

这题数据真的是太弱了吧。。。我开始用认为是错误的代码提交就AC了,但一直不知道哪里的问题。。。最后发现判断的条件反了。。。。不知道为什么反过来也行。。。。。

这题主要是要通过判断是否时间比之前的多来防止无休止的循环。

代码如下:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

typedef struct{
	int x;
	int y;
	int step;
	int time;
} Point;

int T, N, M;
int map[9][9];
int mark[9][9];
int moves[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
Point begins;
 
void BFS(){
	queue<Point> q;
	q.push( begins );	
	mark[begins.x][begins.y] = begins.time;
	while( !q.empty() ){
		Point p;
		p = q.front();
		q.pop();
		for( int i = 0; i < 4; i++ ){
			Point temp = p;
			temp.x += moves[i][0];
			temp.y += moves[i][1];
			temp.step++;
			temp.time--;
			//下面的里面改成temp.x > M || temp.y > N竟然也能过.....太神奇了....
			if( temp.x < 0 || temp.x >= N || temp.y >= M || temp.y < 0 || temp.time <= 0 || map[temp.x][temp.y] == 0 ){
				continue;
			}
			if( map[temp.x][temp.y] == 3 && temp.time > 0 ){
				cout << temp.step << endl;
				return;
 			}else if( map[temp.x][temp.y] == 4 ){
				temp.time = 6;
			} 
			if( mark[temp.x][temp.y] < temp.time ){
				mark[temp.x][temp.y] = temp.time;
 				q.push( temp );
			}
		}
	}
	cout << -1 << endl;
}

int main(){
	cin >> T;
	while( T-- ){
		cin >> N >> M;
		memset( map, 0, sizeof( map ) );
		for( int i = 0; i < N; i++ ){
			for( int j = 0; j < M; j++ ){
				cin >> map[i][j];
				if( map[i][j] == 2 ){
					begins.x = i;
					begins.y = j;
					begins.step = 0;
					begins.time = 6;
				}
				mark[i][j] =0;
			}
		}
		BFS();
	}
	return 0;
}

 

抱歉!评论已关闭.