注册 登录
编程论坛 数据结构与算法

怎么样把这个程序改写成求所有路径中最长的路径长度并显示

童国顺 发布于 2011-03-26 21:16, 395 次点击
#include<stdio.h>
#define m 4
#define n 4
#define maxsize 100
int mg[m+2][n+2]={
    {1,1,1,1,1,1},
    {1,0,0,0,1,1},
    {1,0,1,0,0,1},
    {1,0,0,0,1,1},
    {1,1,0,0,0,1},
    {1,1,1,1,1,1}
};
struct
{
    int i;int j;int di;
}stack[maxsize],path[maxsize];
int top=-1;
int count=1;
int maxlen=maxsize;
void mgpath()
{
    int i,j,di,find,k;
    top++;stack[top].i=1;stack[top].j=1;stack[top].di=-1;mg[1][1]=-1;
    while(top>-1)
    {
        i=stack[top].i;j=stack[top].j;di=stack[top].di;
        if(i==m&&j==n)
        {
            printf("%4d:",count++);
            for(k=0;k<=top;k++)
            {
                printf("(%d %d)",stack[k].i,stack[j].j);
                if((k+1)%5==0)printf("\n\t");
            }
            printf("\n");
            if(top+1<maxlen)
            {
                for(k=0;k<=top;k++)
                    path[k]=stack[k];
                maxlen=top+1;
            }
            mg[stack[top].i][stack[top].j]=0;
            top--;
            i=stack[top].i;j=stack[top].j;di=stack[top].di;
        }
        find=0;
        while(di<4&&find==0)
        {
            di++;
            switch(di)
            {
            case 0:i=stack[top].i-1;j=stack[top].j;break;
            case 1:i=stack[top].i;j=stack[top].j+1;break;
            case 2:i=stack[top].i+1;j=stack[top].j;break;
            case 3:i=stack[top].i;j=stack[top].j-1;break;
            }
            if(mg[i][j]==0) find=1;
        }
        if(find==1)
        {
            stack[top].di=di;
            top++;
            stack[top].i=i;
            stack[top].j=j;
            stack[top].di=-1;
            mg[i][j]=-1;
        }
        else
        {
            mg[stack[top].i][stack[top].j]=0;
            top--;
        }
    }
    printf("最长路径如下:\n");
    printf("长度:  %d\n",maxlen);
    printf("路径:");
    for(k=0;k<maxlen;k++)
    {
        printf("(%d %d)",path[k].i,path[k].j);
        if((k+1)%5==0) printf("\n\t");
    }
    printf("\n");
}
void main()
{
    printf("迷宫是有路径如下:\n");
    mgpath();
}
2 回复
#2
童国顺2011-03-27 16:08
帮下了。哎  怎么这个问题都没有人帮啊?难道是太容易了????????
#3
寒风中的细雨2011-03-28 09:23
怎样求最长的?
1