POJ1915

摘要:BFS, 注意

1。坐标(x,y)对应数组的位置是array[y][x]

2。每个测试数据前要清空队列(白耗了好几个小时,汗……)

 

#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;
    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()
{
   
    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;
            }
        }           
        while( !q.empty() ){
            q.pop();
        }
        BFS();
       
        cout << finish.dist << endl;   
        n--;       
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值