【发布时间】: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