POJ 1429 BFS+优先队列

7 篇文章 0 订阅
2 篇文章 0 订阅

题目:http://poj.org/problem?id=3984

很经典用BFS解决的了。

#include<iostream>  
#include<string.h>  
#include<queue>  
#define INF 1e18
#define inf 1e9
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const int n = 5;
int dx[]={1,-1,0,0};
int dy[]={0,0,-1,1};
bool mp[6][6];
struct node{
    int x,y,step,nx,ny;
    bool operator < (const node &n1)const{
        return step > n1.step;
    }
    void count(){
        this->step = (n-x)+(n-y);
    }
};
struct node1{
    int nx,ny;
    void init(node n){
        this->nx = n.nx;
        this->ny = n.ny;
    }
};
priority_queue<node> q;
node1 m[6][6];
bool outside(node n1){
    if(mp[n1.x][n1.y]) return false;
    if(n1.x > n || n1.x < 1) return false;
    if(n1.y > n || n1.y < 1) return false;
    return true;
}
void bfs(){
    while(!q.empty()) q.pop();
    node now,next;
    now.x = 1,now.y = 1;
    now.count();
    q.push(now);
    while(!q.empty()){
        now = q.top();
        q.pop();
//      cout<<now.x<<' '<<now.y<<endl;
        for(int i = 0 ; i < 4 ; i++){
            next.x = now.x+dx[i];
            next.y = now.y+dy[i];
            next.nx = now.x,next.ny = now.y;
            if(!outside(next)) continue;
            m[next.x][next.y].init(next);
            mp[next.x][next.y] = true;
            next.count();
            q.push(next);
            if(next.x == n&&next.y ==n) return;
        }
    }   
}
void print(int x,int y){
    if(x != 1||y != 1)
        print(m[x][y].nx,m[x][y].ny);
    cout<<"("<<x-1<<", "<<y-1<<")"<<endl;
}
int main(){
    memset(m,0,sizeof(m));
    for(int i = 1 ; i <= n ; i++)
        for(int j = 1 ; j <= n ; j++)   
        cin>>mp[i][j];
    bfs();  
    print(5,5);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值