#include <stdio.h>
#include "time.h"
#include <stdlib.h>
#include "math.h"
#define N 50
#define M 30
int visit(int, int);
int maze[N][M] ;
int success = 0;
int startI,startJ,endI,endJ; // 入口和出口
int main() {
int i, j;
srand(time(0));
for (i=0;i<N;i++)
{
for (j=0;j<M;j++)
{
if (i==0||i==N-1||j==0||j==M-1)
{
maze[i][j]=2;
}
else
{
maze[i][j]=rand()%200;
if (maze[i][j]<70)
{
maze[i][j]=2;
}
else
{
maze[i][j]=0;
}
}
}
}
for (i=1;i<=N-2;i++)
{
for (j=1;j<=M-2;j++)
{
if (maze[i+1][j]==0&&maze[i-1][j]==0&&maze[i][j-1]==0&&maze[i][j+1]==0) //孤独的一个墙不要
{
maze[i][j]=0;
}
}
}
for (i=1;i<=N-2;i++)
{
for (j=1;j<=M-2;j++)
{
if (maze[i+1][j+1]==2&&maze[i+1][j]==2&&maze[i][j+1]==2&&maze[i][j]==2)//把结块的墙分开
{
maze[i][j]=0;
}
}
}
printf("显示迷宫:/n");
for(i = 0; i < N; i++) {
for(j = 0; j < M; j++){
if(maze[i][j] == 2)
printf("█");
else
printf(" ");
}
printf("/n");
}
printf("请输入起点坐标:/n");
scanf("%d%d",&startI,&startJ);
while(maze[startI][startJ]!=0)
{printf("请输入的起点坐标是墙,请重新输入!/n");
printf("请输入起点坐标:/n");
scanf("%d%d",&startI,&startJ);}
printf("请输入终点坐标:/n");
scanf("%d%d",&endI,&endJ);
while(maze[endI][endJ]!=0)
{printf("请输入的终点坐标是墙,请重新输入!/n");
printf("请输入终点坐标:/n");
scanf("%d%d",&endI,&endJ);
}
if(visit(startI, startJ) == 0)
printf("/n没有找到出口!/n");
else {
printf("/n显示路径:/n");
for(i = 0; i < N; i++) {
for(j = 0; j < M; j++) {
if(maze[i][j] == 2)
printf("█");
else if(maze[i][j] == 1)
printf("◇");
else
printf(" ");
}
printf("/n");
}
}
return 0;
}
int visit(int i, int j) {
maze[i][j] = 1;
if(i == endI && j == endJ)
success = 1;
if(success != 1 && maze[i][j+1] == 0) visit(i, j+1);
if(success != 1 && maze[i+1][j] == 0) visit(i+1, j);
if(success != 1 && maze[i][j-1] == 0) visit(i, j-1);
if(success != 1 && maze[i-1][j] == 0) visit(i-1, j);
if(success != 1) //注意
maze[i][j] = 0; //注意
return success;
}