1.题目描述:——迷宫问题
寻找走出迷宫的路径。
2.问题分析:
解决迷宫路径问题,采取深度优先搜索算法,进入迷宫后开始搜索路径,每当遇到岔路,先沿其中一条路线进行搜索,
如果不通则转向另一条路线进行搜索,以此类推,直至搜索完所有路线。
3.代码实现:
#include <stdio.h>
#include <stdlib.h>
int m=14;
int n=17;
int maze[14][17]={
{ ' ', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' },
{ ' ', ' ', ' ', ' ', '#', '#', '#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#', '#' },
{ '#', ' ', '#', ' ', ' ', '#', '#', ' ', '#', '#', '#', ' ', ' ', '#', '#', '#', '#' },
{ '#', ' ', '#', '#', ' ', ' ', ' ', ' ', '#', '#', '#', '#', ' ', ' ', ' ', '#', '#' },
{ '#', ' ', '#', ' ', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', ' ', ' ', '#' },
{ '#', ' ', '#', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#', '#', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', '#', '#', '#', ' ', '#', '#', '#', '#', ' ', ' ', '#' },
{ '#', ' ', '#', '#', '#', ' ', '#', '#', '#', ' ', '#', '#', '#', '#', ' ', '#', '#' },
{ '#', ' ', '#', '#', '#', ' ', '#', '#', ' ', ' ', '#', '#', '#', '#', ' ', '#', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', '#', '#', ' ', ' ', ' ', ' ', '#', '#', ' ', '#', '#' },
{ '#', '#', '#', ' ', ' ', ' ', '#', '#', ' ', '#', '#', ' ', ' ', ' ', ' ', ' ', '#' },
{ '#', '#', '#', ' ', '#', '#', '#', '#', ' ', ' ', ' ', '#', '#', '#', '#', ' ', '#' },
{ '#', '#', '#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', ' ', ' ', ' ', ' ', ' ', ' ' },
{ '#', '#', '#', '#', '#', '#', '#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#', ' ' }
};
int move[4][4]=
{
{0,-1},//left
{1,0}, //down
{0,1}, //right
{-1,0} //up
};
int startx=0,starty=0;
int endx=13,endy=16;
int mark=0;
void printFun()
{
int i,j;
for( i=0;i<m;i++)
{
for( j=0;j<n;j++)
{
if(maze[i][j]!=' '&&maze[i][j]!='#')
{
printf("%c ",maze[i][j]);
}
else
printf("%c ",maze[i][j]);
}
printf("\n");
}
printf("\n");
}
void go(int x,int y)
{
int i;
if(x==endx && y==endy)
{
maze[x][y]=mark+'1';
mark++;
printf("情况%d:\n",mark);
printFun();
return;
}
if(x>=0 && x<m && y>=0 && y<n)
{
if(maze[x][y]!=' ')
return;
maze[x][y]=mark+'1';
for( i=0;i<4;i++)
{
x+=move[i][0];
y+=move[i][1];
go(x,y);
x-=move[i][0];
y-=move[i][1];
}
maze[x][y]=' ';
}
}
int main()
{
printFun();
go(0,0);
return 0;
}

400

被折叠的 条评论
为什么被折叠?



