#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <string.h>
#include<math.h>
#include<stdlib.h>
char maze[100][100];
int step[15][15];
int n, m;
int sm,sn,em,en;
int dn[4]={ 0, 1, 0, -1 };
int dm[4]={ 1, 0, -1, 0 };
struct stack{
int data[100];
int top;
};
struct stack S;
void push(int a) //入栈
{
S.data[S.top] = a;
S.top++;
}
int pop() //出栈
{
S.top--;
return S.data[S.top];
}
int empty() //检查栈是否为空
{
if (S.top == 0)
return 0;
else
return 1;
}
int search_next(int now_m,int now_n)
{
int next_m=now_m, next_n=now_n;
for (int i = 0; i < 4; i++)
{
next_m = now_m;
next_n = now_n;
next_m += dm[i];
next_n += dn[i];
if (next_m>=m || next_m<0 || next_n>=n || next_n < 0 || step[next_m][next_n] == 1 || maze[next_m][next_n] == '#')
continue;
else{
return next_m*n + next_n;
}
}
return 0;
}
void maze_path()
{
int now_m=0, now_n=0,e=0;
now_m = sm;
now_n = sn;
do{
if (e=search_next(now_m, now_n)){
push(now_m*n + now_n);
step[now_m][now_n] = 1;
if (now_m == em && now_n == en)
return;
now_m = e / n;
now_n = e%n;
step[now_m][now_n] = 1;
}
else
{
e = pop();
now_m = e / m;
now_n = e%n;
if (e = search_next(now_m, now_n))
{
push(now_m*n + now_n);
now_m = e / m;
now_n = e % n;
step[now_m][now_n] = 1;
}
}
}while(!(now_m==em && now_n==en));
}
void print_path()
{
int count=1;
for (int i = 0; i < S.top; i++){
printf("<%d,%d> ", S.data[i] / n, S.data[i] % n);
count++;
}
printf("<%d,%d>
", em, en);
printf("走出迷宫需要%d步
", count);
}
int main()
{
int i, j;
printf("请输入迷宫行数: ");
scanf("%d", &m);
printf("请输入迷宫列数: ");
scanf("%d", &n);
printf("S表示起点,E表示终点,#表示路障,=表示通路");
printf("请输入迷宫:
");
for (i = 0; i < m; i++)
scanf("%s", maze[i]);
for (i = 0; i < m; i++){
for (j = 0; j < n; j++){
if (maze[i][j] == 'S')
{
sm = i; sn = j;
}
else if (maze[i][j] == 'E')
{
em = i; en = j;
}
}
}
maze_path();
print_path();
system("pause");
return 0;
}
/* 5行迷宫例子
#S#=#
====#
#=#=#
#=#==
###=E
*/
/* 4行迷宫例子
S###
===E
####
####
*/
/*
S##
=##
E##
*/