zoukankan      html  css  js  c++  java
  • 输入一个矩阵,输入初始坐标和目的坐标,输出最短路径(之一)及路径的各个坐标

    //例如
    //1 1 1 0 0 1
    //0 1 1 1 0 0
    //0 0 0 0 0 0
    //0 0 1 1 0 0
    //0 0 0 0 0 0
    //1 1 1 0 0 1
    //3 1 1 4
    #include<stdio.h>
    #include<string.h>
    #include<queue>
    using namespace std;
    struct stu
    {
        int x,y,step;
        int a[50];
    } s;
    int b[10][10],startx,starty,endx,endy,fx[4][2]= {0,1,0,-1,1,0,-1,0};
    void bfs()
    {
        int i;
        queue<stu>q;
        stu t;
        s.step=0,s.x=startx,s.y=starty,s.a[s.step]=(s.x-1)*6+s.y,b[s.x][s.y]=1;
        q.push(s);
        while(!q.empty())
        {
            s=q.front();
            q.pop();
            if(s.x==endx&&s.y==endy)
            {
                printf("%d ",s.step);
                for(i=0; i<=s.step; i++)
                    printf("%d %d ",s.a[i]%6?s.a[i]/6+1:s.a[i]/6,s.a[i]%6?s.a[i]%6:6);
                break;
            }
            for(i=0; i<4; i++)
            {
                t.x=s.x+fx[i][0],t.y=s.y+fx[i][1];
                memcpy(t.a,s.a,sizeof(t.a));//s复制给t
                if(t.x>=1&&t.x<=6&&t.y>=1&&t.y<=6&&!b[t.x][t.y])
                {
                    t.step=s.step+1,t.a[t.step]=(t.x-1)*6+t.y;
                    q.push(t);
                    b[t.x][t.y]=1;
                }
            }
        }
    }
    int main()
    {
        int i,j;
        for(i=1; i<=6; i++)
            for(j=1; j<=6; j++)
                scanf("%d",&b[i][j]);  // 1表示墙,0表示路。
        scanf("%d%d%d%d",&startx,&starty,&endx,&endy);
        bfs();
    }

  • 相关阅读:
    第七课 GDB调试 (下)
    设计模式之原型模式
    设计模式之再读重构
    设计模式之代理模式
    设计模式之建造者模式
    设计模式之模板方法模式
    设计模式之抽象工厂模式
    设计模式之工厂模式
    设计模式之单例模式
    设计模式之6大原则
  • 原文地址:https://www.cnblogs.com/nyist-xsk/p/7264930.html
Copyright © 2011-2022 走看看