最短路径 矩阵 part1

/*给出m,n是矩阵的行列数 接下来m行每行n个数字*/
#include<stdio.h>
#define size 50
typedef struct{ int value;char direc;} node;
void shortpath(node graph[size][size],int m,int n);
void outpath(node graph[size][size],int m,int n);
/*不要struct最后少了;*/
int main()
{
    int m,n,a;
    node graph[size][size];
    scanf("%d %d",&m,&n);
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            scanf("%d",&a);
            graph[i][j].value=a;
        }
    }/*读入数据完毕*/
    /*初始化记录方向以及每个结点用最短路径代替数值*/
    shortpath(graph,m,n);
    printf("%d\n",graph[m-1][n-1].value);
    outpath(graph,m,n);
}
/*不用传指针直接改了*/
void shortpath(node graph[size][size],int m,int n)
{
    /*因为只能向下或者向右所以第一排和第一列可以初始化*/
    for(int i=1;i<n;i++)
    {graph[0][i].value+=graph[0][i-1].value;
        graph[0][i].direc='R';}
    for(int j=1;j<m;j++)
    {graph[j][0].value+=graph[j-1][0].value;
        graph[j][0].direc='D';}
    for(int i=1;i<m;i++)
    {
        for(int j=1;j<n;j++)
        {
           if(graph[i-1][j].value>graph[i][j-1].value)
           {
               graph[i][j].value+=graph[i][j-1].value;
               graph[i][j].direc='R';
           }
            else
            {
                graph[i][j].value+=graph[i-1][j].value;
                graph[i][j].direc='D';
            }
        }
    }
}
void outpath(node graph[size][size],int m,int n)
{
    if(m==1&&n==1)
        return;
    if(graph[m-1][n-1].direc=='D')
    {
        outpath(graph,m-1,n);
        printf("%c",'D');
    }
    else
    {
        outpath(graph,m,n-1);
        printf("%c",'R');
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值