Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

大牛帮给看下,BFS, 被郁闷了好几个小时了,测试数据过了,打印过程看了下也没发现错,就是WA ,郁闷。。

Posted by TurnAround at 2009-10-18 21:29:53 on Problem 1915
#include <iostream>
#include <queue>
using namespace std;

typedef struct Node{
	int x;
	int y;
	int dist;
}Node;

queue<Node> q;
Node start;
Node finish;
int length = 0;

const int size = 300;
const int offset_num = 8;
int offset_x[offset_num+1] = {0};
int offset_y[offset_num+1] = {0};

int graph[size+1][size+1] = {0};
void initOffset()
{
	offset_x[1] = -2;
	offset_x[2] = -1;
	offset_x[3] = 1;
	offset_x[4] = 2;
	offset_x[5] = 2;
	offset_x[6] = 1;
	offset_x[7] = -1;
	offset_x[8] = -2;

	offset_y[1] = -1;
	offset_y[2] = -2;
	offset_y[3] = -2;
	offset_y[4] = -1;
	offset_y[5] = 1;
	offset_y[6] = 2;
	offset_y[7] = 2;
	offset_y[8] = 1;
}

bool checkOffset(int i, Node current)
{
	int x = current.x + offset_x[i];
	int y = current.y + offset_y[i];
	if(x<0 || x>=length || y<0 || y>=length){
		return false;
	}

	if(graph[y][x] > 0){
		return false;
	}

	return true;
}

void BFS()
{
	if(start.x==finish.x && start.y==finish.y){
		finish.dist = 0;
		return;
	}
	Node current = start;
	int debug_count = 0;
	while(true){
		bool find = false;
		if(debug_count++ < 100){
			cout << current.x << " " << current.y << endl;
			for(int i=0; i<length; i++){
				for(int j=0; j<length; j++){
					cout << graph[i][j] << " "; 
				}
				cout << endl;
			}
			cout << "\n\n\n";
		}
		for(int i=1; i<=offset_num; i++){
			if( checkOffset(i, current) ){
				Node next;
				next.x = current.x+offset_x[i];
				next.y = current.y+offset_y[i];
				next.dist = current.dist + 1;
				if(next.x==finish.x && next.y==finish.y){
					find = true;
					finish.dist = next.dist;
					break;
				}		
				q.push(next);			
				graph[next.y][next.x] = next.dist;
			}
		}	
		if( find ){
			break;
		}
		if( q.empty() ){
			break;
		}
		
		current = q.front();
		q.pop();
	}

}

int main()
{
	
	int n = 0;
	cin >> n;
	initOffset();
	
	while( n > 0 ){
		cin >> length;
		cin >> start.x >> start.y >> finish.x >> finish.y;
		start.dist = finish.dist = 0;

		for(int i=0; i<length; i++){
			for(int j=0; j<length; j++){
				graph[i][j] = 0;
			}
		}			

		BFS();
		
		cout << finish.dist << endl;	
		n--;		
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator