【问题标题】:the path to a point in a matrix. Want to solve it by DP矩阵中点的路径。想通过DP解决
【发布时间】:2015-01-13 10:25:01
【问题描述】:

给定的矩阵是问题矩阵。将单元格 0,0 标记为 2 以显示入口点。我们必须找到到达元素 9 的路径。我使用递归回溯并将有效路径标记为 2,这将导致元素 9。有人可以帮助我使用 DP 实现它。

include <stdio.h>
int path(int [][7],int ,int);
static int exitstack=0;
int main(void) {
    int result,i,j;
    int arr[7][7]={
    {2,1,1,1,1,1,1},
    {0,1,1,0,0,0,1},
    {0,1,0,1,1,0,1},
    {1,0,9,0,1,1,1},      //the problem matrix
    {1,0,1,0,1,1,0},
    {1,1,1,1,1,0,1},
    {1,0,0,0,0,0,1}
    };
    path(arr,0,0);

    for(i=0;i<7;++i)
    {
        for(j=0;j<7;++j)
            printf("%d",arr[i][j]);

        printf("\n");

    }

    return 0;
}

int path(int p[7][7],int x,int y)
{
    int i;
    if(p[x][y]==9)
    {
        exitstack=1;
        return 1;
    }

    for(i=1;i<=4;++i)
    {

        if(i==1) //moving right
        {


            if((y+1)<7)
            {
                if(p[x][(y+1)]==9)
                    path(p,x,(y+1));

                if(p[x][(y+1)]==1)
                {
                    p[x][(y+1)]=2;
                    if(path(p,x,(y+1))) 
                        return 1;
                }
            }
        }
        if(i==2) //moving up
        {

            if((x-1)>0)
            {
                if(p[(x-1)][y]==9)
                    path(p,x-1,y);

                if(p[(x-1)][y]==1)
                {
                    p[x-1][y]=2;
                    if(path(p,x-1,y))
                        return 1;

                }

            }   
        }


        if(i==3) //moving left
        {

            if(y-1>0)
            {
                if(p[x][(y-1)]==9)
                    path(p,x,y-1);

                if(p[x][(y-1)]==1)
                {
                    p[x][(y-1)]=2;
                    if(path(p,x,y-1))
                        return 1;

                }
            }
        }
        if(i==4) //moving down
        {

            if(x+1<7)
            {
                if(p[x+1][y]==9)
                    path(p,x+1,y);

                if(p[x+1][y]==1)
                {
                    p[x+1][y]=2;
                    if(path(p,x+1,y))
                        return 1;
                }
            }
        }
    }   

    if(p[x][y]==9)
    {

        return 1;
    }
    else
    {
        if(exitstack==1)
            return 1;
        else
        {
            p[x][y]=0;  
            return 0;
        }
    }

}

【问题讨论】:

  • “DP”的缩写是什么?
  • 您对特定路径感兴趣还是任意路径就足够了?在后一种情况下,DFS 就足够了。
  • 我想找到最短的路径。使用我的代码,我只能找到一条路径,它可能是最短的,也可能不是最短的。

标签: c dynamic-programming


【解决方案1】:

如果您所说的 DP 是指动态规划,您可以尝试使用 D* 算法。在这里描述有点太长了,但是您可以在此处 (http://www.cs.cmu.edu/~ggordon/likhachev-etal.anytime-dstar.pdf) 或此处 (http://en.wikipedia.org/wiki/D*) 阅读更多相关信息,或在 Google 上搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2012-11-24
    • 2019-02-27
    • 1970-01-01
    • 2022-01-20
    • 2021-06-18
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多