您的位置:首页 > 其它

POJ2243

2009-10-19 19:55 190 查看
摘要:和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 = 8;

const int size = 8;

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;

while(true){

bool find = false;

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()

{

initOffset();

string str_start, str_finish;

while( cin >> str_start >> str_finish ){

start.x = str_start.at(0)-'a';

start.y = str_start.at(1)-'1';

finish.x = str_finish.at(0)-'a';

finish.y = str_finish.at(1)-'1';

start.dist = finish.dist = 0;

for(int i=0; i<=length; i++){

for(int j=0; j<=length; j++){

graph[i][j] = 0;

}

}

while( !q.empty() ){

q.pop();

}

BFS();

cout << "To get from " << str_start << " to " << str_finish << " takes " << finish.dist << " knight moves." << endl;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: