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纪念

Posted by team162 at 2010-05-20 21:45:41 on Problem 2243
//============================================================================
// Name        : PKU-ACM.cpp
// Author      : jarvis
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C, Ansi-style
//============================================================================
#include <iostream>
#include <string>
#include <map>
#include <deque>
#include <queue>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cstdio>
#include <cstring>
using namespace std;
#define repeat(i,beg,end) for(int i=beg;i<end;++i)

struct node{
	int x,y,sum;
	node(int x=0,int y=0,int s=0):x(x),y(y),sum(s){}
};
bool flag[10][10];
int dx[]={1,-1, 2,-2, 1, -1,2 ,-2};
int dy[]={2, 2, 1, 1,-2, -2,-1,-1};
char s[4],t[4];
bool over(int x)
{
	return x>7||x<0;
	}
int bfs(node a,node b)
{
	queue<node> q;
	memset(flag,0,sizeof(flag));
	q.push(a);
	flag[a.x][a.y]=true;

	while(!q.empty())
	{
		int x=q.front().x;
		int y=q.front().y;
		if(x==b.x&&y==b.y)
			return q.front().sum;
		for(int i=0;i<8;++i)
		{
			if(!over(x+dx[i])&&!over(y+dy[i])&&!flag[x+dx[i]][y+dy[i]])
			{
				q.push(node(x+dx[i],y+dy[i],q.front().sum+1));
			}
		}
		q.pop();
	}
	return -1;
	}
int main()
{
	while(cin>>s>>t)
	{
		int ans=bfs(node(s[0]-'a',s[1]-'1'),node(t[0]-'a',t[1]-'1'));
		cout<<"To get from "<<s<<" to "<<t<<" takes "<<ans<<" knight moves."<<endl;
	}


	return 0;
}

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