1.迷宫寻物:
n*m 矩阵中,1表示障碍,0表示通路,起始点任意,假设坐标为(0,0),目标点为(3,2),
找到最短路径到达目标点。
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
这类问题一般使用深度优先搜索(DFS)。其实这个算法是有步骤的。
int n,m,p,q,mins=999999;
int book[51][51];
int a[5][4]={{0,0,1,0},{0,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1}};
void dfs(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<mins)
mins = step;
//返回到上一次调用dfs的地方
return;
}
//尝试每一种可能
for(k=0;k<=3;k++)
{
tx=x+next[k][0];
ty=y+next[k][1];
//判断是否越界
if(tx<0||tx>n-1|ty<0||ty>m-1)
continue;
//判断是否为障碍物或者未走过
if(a[tx][ty]==0&&book[tx][ty]==0)
{
book[tx][ty] = 1;//标记这点已经走过
dfs(tx,ty,step+1);//开始尝试下一个点
book[tx][ty] = 0;//尝试结束,取消这个点的标记,回溯中可再次经过此点
}
}
return;
}
void main()
{
int i,j,startx,starty;
n=5,m=4; //5行4列
startx=0,starty=0;//起始点
p=3;q=2; //目标点
book[startx][starty]=1;
dfs(startx,starty,0);
printf("%d",mins);
getchar();
}
2.矩阵累积之和最大路径
n*m的矩阵,每个格一个数,一个人从(0,0)走到(n,n),只能向右或者向下走,问怎么走,经过的格子的数字之和最大, 输出路径
class point
{
public:
int x;
int y;
};//路径坐标
point pp;
vector<point> way;
vector<point> tempway;
int n,m,mins=0;
int book[51][51];
int a[4][4]={{1,2,3,4},{4,5,60,5},{8,9,10,11},{12,13,14,15}};
int sum;
void dfs(int x,int y)
{
int next[2][2]={{0,1},//向右走
{1,0}//向下走
};
int tx,ty,k;
//判断是否到达目标位置,判断边界
if(x==n-1&&y==m-1)
{
if(sum>mins)
{
mins = sum;
way=tempway;
}
//返回到上一次调用dfs的地方
return;
}
//尝试每一种可能
for(k=0;k<=1;k++)
{
tx=x+next[k][0];
ty=y+next[k][1];
//判断是否越界
if(tx<0||tx>n-1||ty<0||ty>m-1)
continue;
//判断是否为障碍物或者未走过
if(book[tx][ty]==0)
{
pp.x=tx;
pp.y=ty;
tempway.push_back(pp);
sum = sum+a[tx][ty];
book[tx][ty] = 1;//标记这点已经走过
dfs(tx,ty);//开始尝试下一个点
book[tx][ty] = 0;//尝试结束,取消这个点的标记,回溯中可改变路径
sum = sum-a[tx][ty];
tempway.pop_back();
}
}
return;
}
void main()
{
n=4,m=4; //4行4列
sum =a[0][0];
book[0][0]=1;
pp.x=0;pp.y=0;
tempway.push_back(pp);
dfs(0,0);
printf("%d\n",mins);
cout<<"路径为"<<endl;
for(int i=0;i<way.size();i++)
cout<<way.at(i).x<<' '<<way.at(i).y<<endl;
getchar();
}
这两道题的核心算法是一样的。