输入一个矩阵,输入初始坐标和目的坐标,输出最短路径(之一)及路径的各个坐标

来源:互联网 发布:查看80端口占用情况 编辑:程序博客网 时间:2024/05/23 22:18
//例如
//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\n",s.step);
            for(i=0; i<=s.step; i++)
                printf("%d %d\n",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();
}

0 0
原创粉丝点击