zoukankan      html  css  js  c++  java
  • 用queue函数写广搜

    以走迷宫需要的最少步数的代码为例

    #include<stdio.h>
    #include<string.h>
    #include<queue>

    using namespace std;

    struct Note{
    int x,y,s;
    };
    int a[51][51],book[51][51];

    void bfs(Note h, Note t)
    {
    int Next[4][2] = {0};
    int i,tx,ty;
    Note head,tail;
    queue<Note> q;
    q.push(h);
    book[h.x][h.y] = 1;
    while(!q.empty()){
    head = q.front();
    q.pop();
    for(i = 0; i < 4; i++){
    tx = head.x + Next[i][0];
    ty = head.y + Next[i][1];
    if(tx < 0 || tx >= t.x || ty < 0 || ty >= t.y)
    continue;
    if(a[tx][ty] == 0 && book[tx][ty] == 0){
    tail.x = tx;
    tail.y = ty;
    q.push(tail);
    book[tx][ty] = book[head.x][head.y] + 1;
    }
    if(tx == t.x && ty == t.y)
    return ;
    }
    }
    }

    int main()
    {
    Note head,tail;
    int i,j,n,m;
    while(scanf("%d%d",&n,&m) != EOF){
    for(i = 0; i < n; i++)
    for(j = 0; j < m; j++)
    scanf("%d",&a[i][j]);
    memset(book,0,sizeof(book));
    scanf("%d%d%d%d",&head.x,&head.y,&tail.x,&tail.y);
    head.s = 0;
    bfs(head,tail);
    printf("%d ",book[tail.x][tail.y]);
    }
    return 0;
    }

  • 相关阅读:
    回归模型与房价预测
    朴素贝叶斯应用:垃圾邮件分类
    编程实现朴素贝叶斯分类算法
    朴素贝叶斯分类算法
    K-means算法应用:图片压缩
    第八次作业
    第六次作业
    numpy数据集练习
    第五次作业
    中文词频统计
  • 原文地址:https://www.cnblogs.com/didideblog/p/6785818.html
Copyright © 2011-2022 走看看