假设一个地图是n*m的矩阵,能走的格子标为0,不能走的格子标为1,终点位于x=p,y=q处,问,从起点(0,0)到终点最短路径是什么?
首先想如何操作寻路方向:
int next[4][2]={{0,1},//向右走
{1,0},//向下走
{0,-1},//向左走
{-1,0}};//向上走
更新最小值:
void find_out(int x, int y ,int step)
{
if(x==p && y==q){ //此时已经到达终点
if(step<min) //更新最小值
min=step;
return; //
}
}
判断下一步往哪走:
for(k=0;k<=3;k++){
//计算下一个点的坐标:
tx=x+next[k][0];
ty=y+next[k][1];
}
整体代码段:
int min=9999999;
int map[100][100];
int book[100][100];
int find_out(int x,int y,int step)
{
int next[4][2]={{0,1},//向右走
{1,0},//向下走
{0,-1},//向左走
{-1,0}};//向上走
int tx,ty,k;
if(x==p && y==q){ //此时已经到达终点
if(step<min) //更新最小值
min=step;
return step; //退出递归
}
for(k=0;k<=3;k++){
//计算下一个点的坐标:
tx=x+next[k][0];
ty=y+next[k][1];
//判断是否越界:
if(tx<1||tx>n||ty<1||ty>m){
continue;
}
//判断该点是否为障碍物或者已经在路径中;
if(map[tx][ty]==0 && book[tx][ty]==0){
book[tx][ty]=1;
dfs(tx,ty,step+1);
book[tx][ty]=0;
}
}
return step ;
}