2、迷宫问题(必做)(栈与队列)
[问题描述]
利用栈操作实现迷宫问题求解。
[基本要求]
(1)从文件中读取数据,生成模拟迷宫地图,不少于20行20列。
(2)给出任意入口和出口,显示输出迷宫路线。
#include <iostream>
#include <fstream>
#include <queue>
#include <math.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#include <malloc.h>
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100
#define QSIZE 128
#define QINCREMENT 128
#define M 18
#define N 18
using namespace std;
typedef int ElemType;
typedef int Status;
typedef struct Point{
int x,y,direction;//-1 start
}Point;
typedef struct MazeStack{
Point data[MAXSIZE];
int top;
}MazeStack,Stack;
typedef struct Item{
int x,y; //move
}Item;
void setNULL(MazeStack *s){
s->top = -1;
}
Status isEmpty(MazeStack *s){
if(s->top>=0)
return FALSE;
else
return TRUE;
}
MazeStack * push(MazeStack *s,Point x){
if(s->top>MAXSIZE-1){
cout<<"Stack Overflow"<<endl;
return s;
}
else{
s->top++;
s->data[s->top] = x;
return s;
}
}
Point * pop(MazeStack *s){
if(isEmpty(s)){
cout<<"Stack Is Empty";
return NULL;
}
else{
s->top--;
return &(s->data[s->top+1]);
}
}
Point * getTop(MazeStack *s){
if(isEmpty(s)){
cout<<"Stack Empty"<<endl;
return NULL;
}
else{
return &(s->data[s->top]);
}
}
void defineMove(Item xmove[8]){
xmove[0].x = 0 ,xmove[0].y = 1;
xmove[1].x = 1 ,xmove[1].y = 1;
xmove[2].x = 1 ,xmove[2].y = 0;
xmove[3].x = 1 ,xmove[3].y =-1;
xmove[4].x = 0 ,xmove[4].y =-1;
xmove[5].x = -1,xmove[5].y =-1;
xmove[6].x = 1 ,xmove[6].y = 0;
xmove[7].x = -1,xmove[7].y = 1;
}
int main(){
int maze[M+2][N+2];
int x,y;
int i,j,k,direction;
Item xmove[8];
Point start,*p;
MazeStack *s;
const char *fileName = "text2.txt";
char line[1024]={0};
FILE *file = fopen(fileName,"rt");
while(1)
{
// if(EOF == fscanf(file,"%s",line))
// break;
/// cout<<line<<" ";
//int a = atoi(line);
for( i = 0;i<M+2;i++){
for(j = 0;j<N+2;j++){
fscanf(file,"%d ",&maze[i][j]);
//printf("%d ",a[i]);
}
}
if(EOF == fscanf(file,"%s",line))
break;
}
fclose(file);
s = (MazeStack*)malloc(sizeof(MazeStack));
setNULL(s);
defineMove(xmove);
char buff[1024] = {0};
cout<<"Maze is:(0 can pass,1 can't pass )"<<endl;
for( i = 0;i<M+2;i++){
for(j = 0;j<N+2;j++){
cout<<maze[i][j]<<" ";
if(j == 19){
cout<<endl;
}
}
}//
cout<<"Direction: -1 is start; 0 is left,;1 is left and up;2 is up;3 is right and up;4 is right…"<<endl;;
start.x = 1;
start.y = 1;
start.direction = -1;
p = (Point*)malloc(sizeof(Point));
s = push(s,start);
while(!isEmpty(s)){
p = pop(s);
x = p->x;
y = p->y;
direction = p->direction+1;
while(direction<8){
i = xmove[direction].x+x;
j = xmove[direction].y+y;
if(maze[i][j]==0){
p->direction = direction;
s = push(s,*p);
x = i;
y = j;
maze[x][y] = -1;//-1 start
Point nw;
nw.x = x;
nw.y = y;
nw.direction = -1;
s = push(s,nw);
if(x==M&&y==N){
cout<<"Find Out:"<<endl;
while(!isEmpty(s)){
p = pop(s);
cout<<p->x<<" "<<p->y<<" "<<p->direction<<" "<<endl;
}
return 1;
}
else{
break;
}
}
else{
direction++;
}
}
}
return 0;
}