1、方向试探
typedef struct {
int incX,incY;//x,y方向的增量
}Direction;
Direction direct[4];
direct | incX | incY |
---|---|---|
0 | 0 | 1 |
1 | 1 | 0 |
2 | 0 | -1 |
3 | -1 | 0 |
2、Box temp;
x | y | dir |
---|
栈中数据元素的组织
typedef struct{
int x,y;
int dir;//当前元素的位置和方向
}Box;
3、栈
typedef struct{
Box data[MaxSize];
int top;
}SqStack;
4、具体代码
SqStack.h
#ifndef TEST_H
#define TEST_H
#define MaxSize 50//定义栈中元素的最大个数
//栈中数据元素的组织
typedef struct{
int x,y;
int dir;//当前元素的位置和方向
}Box;
//栈
typedef struct{
Box data[MaxSize];
int top;
}SqStack;
//方向试探
typedef struct {
int incX,incY;//x,y方向的增量
}Direction;
//初始化
void InitStack(SqStack &S);
//判栈空
bool StackEmpty(SqStack S);
//进栈
bool Push(SqStack &S,Box x);
//出栈
bool Pop(SqStack &S,Box &x);
//读取栈顶元素
//bool GetTop(SqStack S,Elemtype &x);
//打印栈中元素
void print(SqStack S);
SqStack.cpp
#include "SqStack.h"
#include <iostream>
//初始化
void InitStack(SqStack &S){
S.top=-1;
}
//判栈空
bool StackEmpty(SqStack S){
if(S.top==-1)
return true;
else
return false;
}
//进栈
bool Push(SqStack &S,Box x){
if(S.top==MaxSize-1) return false;
S.top++;
S.data[S.top]=x;//指针加一,在入栈
return true;
}
//出栈
bool Pop(SqStack &S,Box &x){
if(S.top==-1) return false;
x=S.data[S.top--];//先出栈,指针减一
return false;
}
//迷宫问题
bool findpath(int maze[6][6],Direction direct[],SqStack &S){
Box temp;
int x,y,di;//当前坐标和方向
int line,col;//下一个坐标
maze[1][1]=-1;
temp={1,1,-1};
Push(S,temp);
while(!StackEmpty(S)){
Pop(S,temp);
x=temp.x; y=temp.y; di=temp.dir+1;
while(di<4){
line=x+direct[di].incX;
col=y+direct[di].incY;
if(maze[line][col]==0){
temp={x,y,di};
Push(S,temp);
x=line; y=col; maze[x][y]=-1;
if(x==4&&y==4) return true;//迷宫有路
else di=0;
}
else{
di++;
}
}
}
return false;
}
void print(SqStack S){
if(S.top==-1)
printf("栈中元素为空");
while(S.top!=-1){
printf("(%d,%d) ",S.data[S.top].x,S.data[S.top].y);
S.top--;
}
printf("\n");
}
SqStack_main.cpp
#include <iostream>
using namespace std;
#include "SqStack.h"
int main(int argc, char** argv) {
SqStack S;
int maze[6][6]={
{1,1,1,1,1,1},
{1,0,0,1,1,1},
{1,0,0,0,0,1},
{1,0,1,1,1,1},
{1,0,0,0,0,1},
{1,1,1,1,1,1}
};
Direction direct[4]={{0,1},{1,0},{0,-1},{-1,0}};
//初始化
InitStack(S);
//判栈空
StackEmpty(S);
//迷宫问题
bool y=findpath(maze,direct,S);
printf("结果是:%s\n",y==true?"找到出口":"不成功");
print(S);