使用动态数组保存迷宫和迷宫的路径,1表示墙0表示可走。
感觉写法有点naive。
#include <iostream>
using namespace std;
int StepComplete;
void cin_maze(int **a,int row,int column){
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
cin>>a[i][j];
}
}
}
void print(int **maze_path,int h,int w)
{
cout<<"The path is "<<endl;
for (int i = 0;i < h;++i)
{
for (int j = 0;j < w;++j)
{
if(maze_path[i][j])
cout<<"* ";
else cout<<" ";
}
cout << endl;
}
}
//传入迷宫数组,迷宫最终路径数组,行数,列数,首次查找的X坐标,Y坐标,和查找步数
void dfs(int **maze, int **maze_path, int w, int h, int x, int y, int step){
int TempStep=step;//表示传进来时试探到第几步
if (x==(w-2) && y==(h-2))
{
maze_path[x][y]=1;
print(maze_path,w,h);
exit(0);//终止程序执行
}
else
{
StepComplete=0;
while (StepComplete<9)
{
switch (StepComplete)
{
case 0:if (maze[x][y-1]==0&&maze_path[x][y-1]==0)//正左逆时针开始
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x,y-1,StepComplete);
maze_path[x][y]=0;
};break;
case 1:if (maze[x+1][y-1]==0&&maze_path[x][y]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x+1,y-1,StepComplete);
maze_path[x][y]=0;
};break;
case 2:if (maze[x+1][y]==0&&maze_path[x+1][y]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x+1,y,StepComplete);
maze_path[x][y]=0;
};break;
case 3:if (maze[x+1][y+1]==0&&maze_path[x+1][y+1]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x+1,y+1,StepComplete);
maze_path[x][y]=0;
};break;
case 4:if (maze[x][y+1]==0&&maze_path[x][y+1]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x,y+1,StepComplete);
maze_path[x][y]=0;
};break;
case 5:if (maze[x-1][y+1]==0&&maze_path[x-1][y+1]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x-1,y+1,StepComplete);
maze_path[x][y]=0;
};break;
case 6:if (maze[x-1][y]==0&&maze_path[x-1][y]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x-1,y,StepComplete);
maze_path[x][y]=0;
};break;
case 7:if (maze[x-1][y-1]==0&&maze_path[x-1][y-1]==0)
{
maze_path[x][y]=1;
maze[x][y]=2;
dfs(maze,maze_path,h,w,x-1,y-1,StepComplete);
maze_path[x][y]=0;
};break;
case 8:if (x==1 && y==1)
{
cout<<"No Path!"<<endl;
}else
{
StepComplete=TempStep;
return;//试探到第八步的时候返回上一层试探,并把StepComplete设为上一层试探到的步数
}
default:
break;
}
StepComplete++;
}
}
}
int main(){
int row,column;
cout<<"请输入迷宫的行数:"<<endl;
cin>>row;
cout<<"请输入迷宫的列数:"<<endl;
cin>>column;
int **a = new int* [row];
int **maze_path = new int* [row];
for (int i = 0; i < row; i++)
{
a[i] = new int[column];
}
for (int i = 0; i < row; i++)
{
maze_path[i] = new int[column];
}
//将maze_path赋初值
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
maze_path[i][j]=0;
}
}
cout<<"请输入迷宫:"<<endl;
cin_maze(a,row,column);
dfs(a,maze_path,row,column,1,1,0);
return 0;
}