数据结构迷宫源代码

合集下载

数据结构迷宫问题源代码

数据结构迷宫问题源代码

数据结构迷宫问题源代码#include<stdio.h> #include<malloc.h>#include<stdlib.h>#include <conio.h>#include"typedef.h"#include "ADTStack.h"#include"maze.h"#include"CONSTANT.h"#define MAXLEN 15#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW -2#define NULL 0PosType start;PosType end;MazeType maze;bool found;#define MAXLEN 15//迷宫包括外墙最大行列数目#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int Status;// 坐标位置类型typedef struct{int r,c;}PosType;//迷宫中r行c列的位置//迷宫类型typedef struct{int step;PosType seat; //当前的坐标位置int di; //往下一坐标位置的方向}ElemType;//结点类型typedef struct{ ElemType *base;ElemType *top;int size;}Stack;Status FootPrint(MazeType maze,PosType curpos);Status MarkPrint(MazeType maze,PosType curpos);void PrintMaze(MazeType maze);Status MazePath(MazeType maze,PosType start,PosType end);void InitMaze(MazeType maze, char a[MAXLEN][MAXLEN], int row, int col);Status Pass(MazeType maze, PosType curpos);PosType NextPos(PosType curpos,int i);typedef struct NodeType{ElemType data;NodeType *next;}NodeType,*LinkType;//栈类型typedef struct{int r;int c;char arr[MAXLEN][MAXLEN];//可取' ','*','@','#' }MazeType;Status InitStack(Stack &S);//InitStackStatus Push(Stack &S,ElemType e) ;Status Pop(Stack &S, ElemType &e) ;Status DestroyStack(Stack &S);//DestroyStackvoid ClearStack(Stack &S);//ClearStackStatus StackEmpty(Stack S);//StackEmptyint StackLength(Stack S);void StackTraverse(Stack S, Status(*visit)(ElemType e));//创建栈void Initialization(){printf("\n*********************************************************"); printf("\n * CreatMaze--c MazePath--m PrintMaze Quit*"); printf("\n*****************************************************"); printf("\n * Operation: *");printf("\n************************************************");printf("\n\n enter a operation code:c,m,p,q:");}//读入操作命令符,显示提示信息void ReadCommand(char &cmd){do{cmd=getche();}while(!(cmd=='c'||cmd=='m'||cmd=='p'));}//解释ch--具体执行void Interpret(char cmd){switch(cmd){case 'c':{int rnum, cnum, i=0,m=1,n=1;char a2[MAXLEN][MAXLEN];char input[20];char data[1000];printf("\n请输入迷宫数据文件名!\n");scanf("%s",input);FILE *fp;fp=fopen(input,"r");if(!fp){printf("\n不能打开文件\n");break;while(!feof(fp)){fscanf(fp,"%s",&data[i]);if(i==0){rnum=(int)data[i]-(int)'0';}if(i==1){cnum=(int)data[i]-(int)'0';}if(i>=2){if(n>cnum){m++;n=1;}a2[m][n]=data[i];n++;}i++;}fclose(fp);InitMaze(maze, a2, rnum, cnum);printf("\n迷宫建立完成!!\n");break;}case 'm':{printf("\n请输入迷宫入口的坐标,以空格为间隔:--"); scanf("%d %d",&start.r,&start.c);printf("\n请输入迷宫出口的坐标,以空格为间隔:--"); scanf("%d %d",&end.r,&end.c);MazePath(maze, start, end);break;}case 'p':{if(found){printf("\n求解迷宫的结果如下--\n");PrintMaze(maze);}else printf("\n找不到路径!\n");}}void main(){char cmd;printf(" welcome to the game!!! "); Initialization();do{ReadCommand(cmd); //读入一个操作符命令Interpret(cmd); //解释执行命令操作符}while(cmd!='q');}#include "stdio.h"#include "malloc.h"#include"typedef.h"#include"CONSTANT.h"Status InitStack(Stack &S){ // 构造一个空栈SS.base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));if (!S.base) return OVERFLOW; //存储分配失败S.top = S.base;S.size = STACK_INIT_SIZE;return OK;} //InitStackStatus Push(Stack &S,ElemType e){if (S.top - S.base >= S.size){//栈满,追加存储空间S.base = (ElemType*)realloc( S.base,(S.size + STACKINCREMENT)*sizeof (ElemType)); if (!S.base) return OVERFLOW; //存储分配失败S.top = S.base + S.size;S.size += STACKINCREMENT;}*S.top++ = e;return OK;}//PushStatus Pop(Stack &S, ElemType &e){// 若栈不空,则删除S的栈顶元素,// 用e返回其值,并返回OK;// 否则返回ERRORif (S.top == S.base) return ERROR;e = *--S.top;return OK;}//PopStatus DestroyStack(Stack &S){ //释放栈S所占据的存储空间if(!S.base) return ERROR;free(S.base);S.base=NULL;S.top= NULL;return OK;}//DestroyStackStatus ClearStack(Stack &S){ //将栈S清为空栈????S.top=S.base;return OK;}//ClearStackStatus StackEmpty(Stack S){//如果栈为空栈,则返回TRUE,否则返回FALSEif(S.top==S.base)return TRUE;else return FALSE;}//StackEmptyint StackLength(Stack S){ //返回栈S的长度,实际上是栈中元素的个数return S.top-S.base;}//StackLengthStatus StackTraverse(Stack S,Status (*visit)(ElemType e)){ int i;//从栈底到栈顶依次对栈中每个元素调用visit函数,如果visit失败,则操作失败if(S.top==S.base) return ERROR;for(i=0;i<S.top - S.base;i++)if(visit(S.base[i])==ERROR) return ERROR;return OK;} //StackTraverse#include<stdio.h>#include<malloc.h>#include<stdlib.h>#include"typedef.h"#include"CONSTANT.h"#include "ADTStack.h"Status MarkPrint(MazeType maze,PosType curpos){maze.arr[curpos.r][curpos.c]='@';//"@"表示曾走过但不通return OK;}//曾走过而且是通路标记并返回OKStatus FootPrint(MazeType maze,PosType curpos){maze.arr[curpos.r][curpos.c]='*';//"*"表示可通return OK;}PosType NextPos(PosType &curpos,int i){PosType cpos;cpos=curpos;scanf("%d",&i);switch(i){ //1.2.3.4分别表示东,南,西,北方向case 1 : cpos.c+=1;break;case 2 : cpos.r+=1;break;case 3 : cpos.c-=1;break;case 4 : cpos.r-=1;break;}return cpos;}//判断当前位置是否可通Status Pass(MazeType maze, PosType curpos){if(maze.arr[curpos.r][curpos.c]==' ')return TRUE;elsereturn FALSE;}//创建迷宫//按照用户输入的二维数组(或),设置迷宫maze的初值,包括加上边缘一圈的值void InitMaze(MazeType maze, char a[MAXLEN][MAXLEN], int row, int col){maze.r=row;maze.c=col;int i;for( i=0;i<=col+1;i++){a[0][i]='1';a[row+1][i]='1';}for(i=0;i<=row+1;i++){a[i][0]='1';a[i][col+1]='1';}for(i=0;i<=maze.r+2;i++){for(int j=0;j<maze.c+2;j++){if(a[i][j]=='1')maze.arr[i][j]='#';elsemaze.arr[i][j]=' ';}}}Status MazePath(MazeType maze,PosType start,PosType end){//求解迷宫maze中,从入口start到出口end的一条路径,若存在,返回TRUE,否则返回FALSE PosType curpos;int curstep=1;Stack S;bool found;ElemType e;InitStack(S);curpos=start;//设定"当前位置"为"入口位置"found=FALSE;do{if(Pass(maze,curpos)){//当前位置可以通过,即是未曾走到过的通道块留下足迹FootPrint(maze,curpos);//做可以通过的标识e.seat=curpos;e.di=1; //为栈顶元素赋值Push(S,e); //加入路径if(curpos.r==end.r && curpos.c==end.c) found=TRUE;//如果到达终点返回trueelse{curpos=NextPos(curpos,1);curstep++;//下一位置是当前位置的东邻}}else //当前位置不能通过if(!StackEmpty(S)){Pop(S,e);while(e.di==4 && !StackEmpty(S)){MarkPrint(maze,e.seat); //留下不能通过的标记Pop(S,e);curstep--;}if(e.di<4){e.di++; //换下个方向Push(S,e); //curpos=NextPos(e.seat,e.di); //进行探索}}}while(!StackEmpty(S)&&!found);//DestroyStack(S);return found;}//MazePath将标记路径信息的迷宫(字符型方阵)输出到终端(包括外墙) void PrintMaze(MazeType maze){for(int i=0;i<=maze.r+2;i++){for(int j=0;j<=maze.c+2;j++){printf(" %c",maze.arr[i][j]);//输出迷宫}printf("\n");}}。

数据结构迷宫问题的C++代码

数据结构迷宫问题的C++代码

数据结构课程设计——迷宫问题求解代码问题描述及要求:迷宫问题求解输入:第一行n,m表示迷宫大小n*m之后有n行m列,全由01组成,0表示路,1表示墙入口设为(0, 0)出口设为(n-1, m-1)输出:输出从入口到出口的所有不同解,每组解的第一行打印一个数表示第几组解,之后k行表示路径,如:1(0, 0)(0, 1)(1, 1)代码部分(已测试,可直接运行):#include <cstdio>#include <cstring>#define N 255int n,m,cnt;int maze[N][N],step[N][N];struct Point{int x,y;}path[N*N];int oper[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};bool isvaild(int x,int y){if (x >= 0 && x < n && y >= 0 && y < m && !maze[x][y] && !step[x][y])return true;return false;}void dfs(int x,int y,int len){if (x == n-1 && y == m-1){cnt++;printf("%d\n",cnt);for (int i = 0;i < len;i++)printf("(%d,%d)\n",path[i].x,path[i].y);return;}for (int i = 0;i < 4;i++)if (isvaild(x + oper[i][0],y + oper[i][1])){Point tmp;tmp.x = x + oper[i][0];tmp.y = y + oper[i][1];path[len] = tmp;step[tmp.x][tmp.y] = 1;dfs(tmp.x, tmp.y, len+1);step[tmp.x][tmp.y] = 0;}}void work(){step[0][0] = 1;Point cur;cur.x = 0;cur.y = 0;path[0] = cur;dfs(0, 0, 1);}int main(){scanf("%d%d", &n, &m);for (int i = 0;i < n;i++)for (int j = 0;j < m;j++)scanf("%d", &maze[i][j]);cnt = 0;memset(step, 0, sizeof(step));work();return 0;。

栈的应用-迷宫问题-数据结构(C语言版)-源代码(直接运行)

栈的应用-迷宫问题-数据结构(C语言版)-源代码(直接运行)

#include <stdio.h>#include <stdlib.h>#include <string.h>#define STACK_INIT_SIZE 100#define INCREMENT 10typedef struct{int r;int c;}zuobiao;typedef struct{int ord; //在当前坐标上的“标号”zuobiao seat; //坐标int di; //走向下一通道的方向}lujing;typedef struct{int sz[10][10];}Maze;typedef struct SqStack{lujing *base;lujing *top;int size;}SqStack;int initStack(SqStack *s){s->base = (lujing *)malloc(STACK_INIT_SIZE*sizeof(lujing) );if(!s->base)return -1;s->top = s->base;s->size = STACK_INIT_SIZE;return 0;}int push(SqStack *s, lujing e){if(s->top - s->base >= s->size){s->base = (lujing *)realloc(s->base, (s->size+INCREMENT)*sizeof(lujing));if(!s->base)return -1;s->top = s->base+s->size;s->size += INCREMENT;}*s->top++ = e;return 0;}int pop(SqStack *s,lujing *e){if(s->top == s->base)return -1;*e = *(--s->top);return 0;}int isEmpty(SqStack *s){if(s->base == s->top)return 1;elsereturn 0;}int pass( Maze maze,zuobiao dqzb) {if (maze.sz[dqzb.r][dqzb.c]==1)return 1; // 如果当前位置是可以通过,返回1else return 0; // 否则返回0}void footPrint(Maze &maze,zuobiao dqzb) {maze.sz[dqzb.r][dqzb.c]=9;}void markPrint(Maze &maze,zuobiao dqzb) {maze.sz[dqzb.r][dqzb.c]=4;}zuobiao nextPos(zuobiao dqzb, int Dir) {zuobiao xzb;switch (Dir) {case 1:xzb.r=dqzb.r;xzb.c=dqzb.c+1;break;case 2:xzb.r=dqzb.r+1;xzb.c=dqzb.c;break;case 3:xzb.r=dqzb.r;xzb.c=dqzb.c-1;break;case 4:xzb.r=dqzb.r-1;xzb.c=dqzb.c;break;}return xzb;}int mazePath(Maze &maze, zuobiao start, zuobiao end){SqStack *s = (SqStack *)malloc(sizeof(SqStack));initStack(s);zuobiao dqzb = start; // 设定"当前位置"为"入口位置"lujing e;int curstep = 1; // 探索第一步do {if (pass(maze,dqzb)) { // 当前位置可通过,即是未曾走到过的通道块footPrint(maze,dqzb); // 留下足迹e.di =1;e.ord = curstep;e.seat= dqzb;push(s,e); // 加入路径if (dqzb.r == end.r && dqzb.c==end.c)return 0; // 到达终点(出口)dqzb = nextPos(dqzb, 1); // 下一位置是当前位置的东邻curstep++; // 探索下一步} else { // 当前位置不能通过if (!isEmpty(s)) {pop(s,&e);while (e.di==4 && !isEmpty(s)) {markPrint(maze,e.seat);pop(s,&e); // 留下不能通过的标记,并退回一步}if (e.di<4) {e.di++; // 换下一个方向探索push(s, e);dqzb = nextPos(e.seat, e.di); // 当前位置设为新方向的相邻块}}}} while (!isEmpty(s) );return -1;}void main(){printf(" *----Δ迷宫求解Δ----*\n\n");printf("---迷宫如下所示:(说明:0表示墙;1表示可以通过)");printf("\n");Maze maze; //声明mazemaze.sz[0][0]= 0;maze.sz[0][1]= 0;maze.sz[0][2]= 0;maze.sz[0][3]= 0;maze.sz[0][4]= 0;maze.sz[0][5]= 0;maze.sz[0][6]= 0;maze.sz[0][7]= 0;maze.sz[0][8]= 0;maze.sz[0][9]= 0;maze.sz[1][0]= 0;maze.sz[1][1]= 1;maze.sz[1][2]= 1;maze.sz[1][3]= 0;maze.sz[1][4]= 1;maze.sz[1][5]= 1;maze.sz[1][6]= 1;maze.sz[1][7]= 0;maze.sz[1][8]= 1;maze.sz[1][9]= 0;maze.sz[2][0]= 0;maze.sz[2][1]= 1;maze.sz[2][2]= 1;maze.sz[2][3]= 0;maze.sz[2][4]= 1;maze.sz[2][5]= 1;maze.sz[2][6]= 1;maze.sz[2][7]= 0;maze.sz[2][8]= 1;maze.sz[2][9]= 0;maze.sz[3][0]= 0;maze.sz[3][1]= 1;maze.sz[3][2]= 1;maze.sz[3][3]= 1;maze.sz[3][4]= 1;maze.sz[3][5]= 0;maze.sz[3][6]= 0;maze.sz[3][7]= 1;maze.sz[3][8]= 1;maze.sz[3][9]= 0;maze.sz[4][0]= 0;maze.sz[4][1]= 1;maze.sz[4][2]= 0;maze.sz[4][3]= 0;maze.sz[4][4]= 0;maze.sz[4][5]= 1;maze.sz[4][6]= 1;maze.sz[4][7]= 1;maze.sz[4][8]= 1;maze.sz[4][9]= 0;maze.sz[5][0]= 0;maze.sz[5][1]= 1;maze.sz[5][2]= 1;maze.sz[5][3]= 1;maze.sz[5][4]= 0;maze.sz[5][5]= 1;maze.sz[5][6]= 1;maze.sz[5][7]= 0;maze.sz[5][8]= 1;maze.sz[5][9]= 0;maze.sz[6][0]= 0;maze.sz[6][1]= 1;maze.sz[6][2]= 0;maze.sz[6][3]= 1;maze.sz[6][4]= 1;maze.sz[6][5]= 1;maze.sz[6][6]= 0;maze.sz[6][7]= 1;maze.sz[6][8]= 1;maze.sz[6][9]= 0;maze.sz[7][0]= 0;maze.sz[7][1]= 1;maze.sz[7][2]= 0;maze.sz[7][3]= 0;maze.sz[7][4]= 0;maze.sz[7][5]= 1;maze.sz[7][6]= 0;maze.sz[7][7]= 0;maze.sz[7][8]= 1;maze.sz[7][9]= 0;maze.sz[8][0]= 0;maze.sz[8][1]= 0;maze.sz[8][2]= 1;maze.sz[8][3]= 1;maze.sz[8][4]= 1;maze.sz[8][5]= 1;maze.sz[8][6]= 1;maze.sz[8][7]= 1;maze.sz[8][8]= 1;maze.sz[8][9]= 0;maze.sz[9][0]= 0;maze.sz[9][1]= 0;maze.sz[9][2]= 0;maze.sz[9][3]= 0;maze.sz[9][4]= 0;maze.sz[9][5]= 0;maze.sz[9][6]= 0;maze.sz[9][7]= 0;maze.sz[9][8]= 0;maze.sz[9][9]= 0;int i,j,sum;for (i = 0; i < 10; i++) {for (j = 0; j < 10; j++){printf("%4d",maze.sz[i][j]);sum++;}if(sum%10==0)printf("\n");}printf("\n");printf("---请输入1求解路径图:");int a;scanf("%d",&a);if(a==1){zuobiao rukou,chukou;rukou.r=1;rukou.c=1;chukou.r=8;chukou.c=8;mazePath(maze,rukou,chukou);printf("\n");printf("---图解如下所示:(说明:0表示墙;1表示可以通过;4表示走不通;9表示所走的路径)\n");for (i = 0; i < 10; i++) {for (j = 0; j < 10; j++){printf("%4d",maze.sz[i][j]);sum++;}if(sum%10==0)printf("\n");}}}。

数据结构迷宫问题源代码

数据结构迷宫问题源代码

#include<stdio.h>#include<stdlib.h>#include"Status.h"typedef struct{int x;int y;}posType;typedef struct{posType pos;int dirc;}SElemType;#include"SqStack.h"#define Row 12#define Col 12posType nextPos(posType curPos,int d){posType pos;switch(d){case 1: pos.x=curPos.x;pos.y=curPos.y+1;break;case 2: pos.x=curPos.x+1;pos.y=curPos.y;break;case 3: pos.x=curPos.x;pos.y=curPos.y-1;break;case 4: pos.x=curPos.x-1;pos.y=curPos.y;break;}return pos;}Status canGo(posType pos,int M[Row][Col]){if(M[pos.x][pos.y]==0) return TRUE;else return FALSE;}Status Maze(int M[Row][Col],posType start,posType end){ SqStack S;SElemType e;posType curPos;int d,step;InitSqStack(&S,100);curPos=start;d=4;do{if(canGo(curPos,M)){M[curPos.x][curPos.y]=2;e.pos=curPos;e.dirc=d;Push(&S,e);if(curPos.x==end.x&&curPos.y==end.y) break;d=1;curPos=nextPos(curPos,d);}else if(d<4){d++;getTop(S,&e);curPos=nextPos(e.pos,d);}else if(!stackIsEmpty(S)){Pop(&S,&e);d=e.dirc;curPos=e.pos;}}while(!stackIsEmpty(S));if(!stackIsEmpty(S)){Pop(&S,&e);M[e.pos.x][e.pos.y]='e';d=e.dirc;for(step=stackLength(S);step>0;step--){Pop(&S,&e);switch(d){case 1: M[e.pos.x][e.pos.y]=26;break;case 2: M[e.pos.x][e.pos.y]=25;break;case 3: M[e.pos.x][e.pos.y]=27;break;case 4: M[e.pos.x][e.pos.y]=24;break;}d=e.dirc;}M[start.x][start.y]='s';return TRUE;}else return FALSE;}void printMaze(int M[Row][Col],posType start,posType end){int i,j;printf("迷宫:入口(%d,%d),出口(%d,%d)\n",start.x,start.y,end.x,end.y); printf("\t%3c",' ');for(i=0;i<Col;i++)printf("%2d ",i);printf("\n");for(i=0;i<Row;i++){printf("\t%2d",i);for(j=0;j<Col;j++){if(M[i][j]==1)printf("|||");else if(M[i][j]==0)printf(" ");else if(M[i][j]==2)printf(" = ");else printf(" %c",M[i][j]);}printf("\n");}printf("\n");}int main(){int M[Row][Col]={{1,1,1,1,1,1,1,1,1,1,1,1},{1,0,0,0,1,1,0,1,1,1,0,1},{1,0,1,0,0,1,0,0,1,0,0,1},{1,0,1,1,0,0,0,1,1,0,1,1},{1,0,0,1,0,1,0,0,0,0,0,1},{1,1,0,1,0,1,1,0,1,0,1,1},{1,0,0,1,0,0,0,0,1,1,1,1},{1,0,1,0,1,1,1,1,0,0,1,1},{1,0,0,0,0,1,1,0,0,0,1,1},{1,0,1,0,1,0,0,0,1,0,0,1},{1,0,0,0,0,0,1,0,0,1,0,1},{1,1,1,1,1,1,1,1,1,1,1,1} };posType start,end;start.x=1;start.y=1;end.x=10;end.y=10;printMaze(M,start,end);if(Maze(M,start,end)){printf("找到可行路径:\n");printMaze(M,start,end);}else printf("无可行路径!\n");system("pause");return 0;}。

数据结构迷宫源代码

数据结构迷宫源代码

数据结构迷宫源代码数据结构迷宫源代码1.引言在计算机科学中,数据结构是一种组织和存储数据的方式,能够有效地使用和操作这些数据。

迷宫是一种经典的问题,通过使用数据结构,我们可以有效地表示和解决迷宫问题。

本文将介绍如何使用数据结构来表示和解决迷宫问题,并提供相应的源代码。

2.迷宫的定义与表示迷宫可以被定义为一个二维的网格,其中的每个单元格可以是通路或墙壁。

我们可以使用二维数组来表示迷宫,其中的每个元素可以被设定为0代表墙壁,1代表通路。

以下是一个迷宫的示例: ```int[][] maze = {{0, 0, 0, 0, 0},{1, 1, 0, 1, 0},{0, 1, 0, 0, 0},{0, 1, 1, 1, 1},{0, 0, 0, 0, 0}}。

```3.迷宫求解算法3.1 深度优先搜索算法深度优先搜索算法是一种递归的算法,它会尽可能地深入到迷宫中的某个通路,直到无法继续深入为止。

然后回溯到上一个分支点,继续搜索其他的分支。

以下是深度优先搜索算法的代码: ```void dfs(int[][] maze, int row, int col) {// 标记当前位置为已经访问过maze[row][col] = .1。

// 检查周围的四个方向int[] dx = {.1, 1, 0, 0}。

int[] dy = {0, 0, .1, 1}。

for (int i = 0。

i < 4。

i++) {int newRow = row + dx[i]。

int newCol = col + dy[i]。

// 检查新位置是否合法并且是通路if (newRow >= 0 && newRow < maze.length && newCol >= 0 && newCol < maze[0].length &&maze[newRow][newCol] == 1) {dfs(maze, newRow, newCol)。

迷宫程序源代码

迷宫程序源代码

#include"stdio.h"#include"stdlib.h"#define M1 11#define N1 11 /*M1*N1为加上围墙后的迷宫大小*/#define MAX 100 /*定义栈的最大长度*/int M=M1-2;int N=N1-2; /*M*N为原迷宫大小*/typedef struct /*定义栈元素的类型*/{int x,y,dir;}elemtype;typedef struct /*定义顺序栈*/{elemtype stack[MAX];int top;}P;struct moved /*定义方向位移数组的类型*/{int dx;int dy;};void Newmg(int mg[M1][N1]) /*迷宫的初始化*/{int i,j,num;printf("迷宫:\n");for (i=1;i<=M;i++){for (j=1;j<=N;j++){num=(800*(i+j)+1500)%327; /*根据N和M值伪随机产生迷宫*/if((num<150)&&(i!=M||j!=N))mg[i][j]=1;elsemg[i][j]=0;printf("%3d",mg[i][j]);} /*输出迷宫*/printf("\n");}printf("\n");for(i=0;i<=M+1;i++) /*设置迷宫的围墙*/{mg[i][0]=1;mg[i][N+1]=1;}for(j=0;j<=N+1;j++)mg[0][j]=1;mg[N+1][j]=1;}}void Newmove(struct moved move[8]) /*定义存储坐标变量的方向位移*/ {move[0].dx=0;move[0].dy=1; /*寻找方向依次为:东,东南,南,move[1].dx=1;move[1].dy=1; 西南,西,西北,北,东北*/ move[2].dx=1;move[2].dy=0;move[3].dx=1;move[3].dy=-1;move[4].dx=0;move[4].dy=-1;move[5].dx=-1;move[5].dy=-1;move[6].dx=-1;move[6].dy=0;move[7].dx=-1;move[7].dy=1;}void Newstack(P *s) /*初始化栈*/{s->top=-1;}int RuZhan(P *s ,elemtype x) /*将数据元素x压入指针s所指的栈中*/ {if (s->top==MAX-1)return (0); /*如栈满,即压栈失败,则返回0*/ else{s->stack[++s->top]=x;return(1); /*压栈成功,则返回1*/}}elemtype ChuZhan(P *s) /*栈顶元素出栈*/{elemtype elem;if (s->top<0) /*如果栈空,返回空值*/{elem.x=NULL;elem.y=NULL;elem.dir=NULL;return(elem);}elses->top--;return(s->stack[s->top+1]); /*如果栈非空,返回栈顶元素*/}}void Search(int mg[M1][N1],struct moved move[8],P *s){ /*寻找迷宫的通路*/int i,j,dir,x,y,k;elemtype elem;i=1;j=1;dir=0;mg[1][1]=-1; /*设置(1,1)为入口处*/do{x=i+move[dir].dx; /*寻找下一步可行的到达点的坐标*/y=j+move[dir].dy;if(mg[x][y]==0){elem.x=i;elem.y=j;elem.dir=dir;k=RuZhan(s,elem); /*如果可通过,将此点数据压栈*/if(k==0)printf("栈长度太短\n"); /*如果入栈操作返回0,说明栈容量不够*/i=x;j=y;dir=0;mg[x][y]=-1;}else if(dir<7)dir++;else /*如果八个方向都不可行,就退回一步*/ {elem=ChuZhan(s);if (elem.x!=NULL){i=elem.x;j=elem.y;dir=elem.dir+1;}}}while (!((s->top==-1)&&(dir>=7)||(x==M)&&(y==N)));/*循环,直到入口处或出口处为止*/if(s->top==-1) /*如果最终是入口处,则迷宫无通路*/printf("此迷宫无通路\n");else{elem.x=x;elem.y=y;elem.dir=dir;k=RuZhan(s,elem); /*将最后出口的坐标压入栈中*/printf("迷宫通路:\n");printf (" 入口->");i=0;while (i<=s->top){printf("(%d,%d)->",s->stack[i].x,s->stack[i].y); /*显示迷宫通路*/ if(i!=s->top)if((i+1)%4==0)printf("\n");i++;}printf ("出口\n");}}void main() /*寻找迷宫通路程序*/{P *s;int mg[M1][N1];struct moved move[8];Newmg (mg); /*调用函数初始化迷宫*/s=(P*)malloc(sizeof(P));Newstack(s); /*调用函数初始化栈*/Newmove(move); /*调用函数初始化位移数组*/ Search (mg,move,s); /*调用函数寻找迷宫通路*/}。

python自动生成迷宫案例

python自动生成迷宫案例

一、引言Python是一种功能强大的编程语言,它能够实现许多复杂的任务。

在这篇文章中,我们将介绍如何使用Python来生成迷宫。

迷宫是一种具有趣味性的游戏和挑战,通过编程生成迷宫不仅可以帮助我们理解算法和数据结构,还可以提升编程技能。

二、生成迷宫的原理1. 迷宫是由一系列的格子组成的,每个格子有四个边界,分别为上、下、左、右。

在生成迷宫的过程中,我们需要使用数据结构来表示迷宫的格子和边界关系,通常会选择使用二维数组或者图来实现。

2. 生成迷宫的核心算法是深度优先搜索(DFS)或者广度优先搜索(BFS)。

通过这两种算法,我们可以逐步打通迷宫的通道,直到所有的通道都被打通,从而形成一个完整的迷宫。

三、使用Python实现迷宫生成1. 我们需要创建一个空的二维数组来表示迷宫,数组的大小可以根据实际需求进行调整。

我们可以使用一个N×M大小的二维数组来表示迷宫的格子。

2. 接下来,我们可以随机选择一个起始位置作为迷宫的起点,并将该位置标记为已访问过。

我们可以通过DFS或BFS算法来递归打通通道,直到所有的可达位置都被标记为已访问过。

3. 在递归的过程中,我们需要注意避免形成死胡同或者回路,可以采用一些技巧来避免这种情况的发生,例如通过随机选择下一个可访问的位置,并且保证每个位置只能被访问一次。

四、Python代码示例下面是一个简单的Python代码示例,用来生成一个5×5的迷宫:```pythonimport randomdef generate_maze(rows, cols):maze = [[0 for _ in range(cols)] for _ in range(rows)]dfs(maze, 0, 0)return mazedef dfs(maze, x, y):directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]random.shuffle(directions)for dx, dy in directions:nx, ny = x + dx, y + dyif 0 <= nx < len(maze) and 0 <= ny < len(maze[0]) and maze[nx][ny] == 0:maze[nx][ny] = 1dfs(maze, nx, ny)```五、总结通过本文的介绍,我们了解了使用Python来生成迷宫的原理和实现方法。

数据库迷宫代码

数据库迷宫代码

#include<stdio.h>#include<stdlib.h>/*数据定义*/typedef enum { ERROR, OK } Status;typedef struct{int row; //row表示"行"号int line; //line表示"列"号}PosType; //位置的元素类型typedef struct{int ord; //该通道在路径上的"序号"PosType seat; //通道块在迷宫中的"坐标位置"int di; //从此通道走向下以通道块的"方向"}SElemType; //栈的元素类型typedef struct{SElemType * base;SElemType * top;int stacksize;}SqStack;/*函数原型说明*/Status InitStack(SqStack &S); //创建一个空栈SStatus Push(SqStack &S,SElemType &a); //插入新元素aStatus Pop(SqStack &S,SElemType &a); //删除栈顶元素,a返回其值Status StackEmpty(SqStack S); //检查是否空栈Status MazePath(int maze[12][12],SqStack &S, PosType start, PosType end); //找通路void Initmaze(int maze[12][12],int x,int y); //初始化迷宫void printmaze(int maze[12][12],int x,int y); //显示迷宫Status Pass(int maze[12][12],PosType CurPos); //判断当前位置是否可通void Markfoot(int maze[12][12], PosType CurPos); //标记当前位置不可通PosType NextPos(PosType CurPos, int Dir); //进入下一位置void printpath(int maze[12][12],SqStack S,int x,int y,PosType start,PosType end); //显示通路/*主函数*/void main (void){PosType start,end;int t=0;SqStack S;int maze[12][12];do{if(t!=0)printf("\n");for(int i=0;i<20;i++){printf("* ");}if(t==0){printf("\n*\t欢迎来到迷宫世界\t * \n");printf("*\t 1.设置迷宫\t\t * \n");}else{printf("\n* 请继续选择:\t\t\t * \n");printf("*\t 1.设置迷宫\t\t * \n");}printf("*\t 2.设置迷宫路径\t\t * \n");printf("*\t 3.输出迷宫通路路径\t * \n"); printf("*\t 4.结束\t\t\t *\n");t++;for(int j=0;j<20;j++){printf("* ");}printf("\n");int s;printf("请选择:");scanf("%d",&s);int aa; int x,y;switch(s){case 1://1.初始化迷宫aa=1;printf("迷宫设置:请输入\n"); //设置迷宫大小do{printf("行X(x<10)=");scanf("%d",&x);printf("列Y(y<10)=");scanf("%d",&y);if(x<1 || x>10||y<1 || y>10){printf("输入错误!\n");}}while(x<1 || x>10||y<1 || y>10);Initmaze(maze,x,y); //初始化迷宫printmaze(maze,x,y); //显示所创建的迷宫break;case 2://寻找迷宫路径if(aa==1){aa=2; //设置入口和出口do{printf("输入入口行坐标:");scanf("%d",&start.row);if(start.row>x)printf("输入错误!\n");}while(start.row>x);do{printf("输入入口列坐标:");scanf("%d",&start.line);if(start.line>y)printf("输入错误!\n");}while(start.line>y);do{printf("输入出口行坐标:");scanf("%d",&end.row);if(end.row>x)printf("输入错误!\n");}while(end.row>x);do{printf("输入出口列坐标:");scanf("%d",&end.line);if(end.line>y)printf("输入错误!\n");}while(end.line>y);}elseprintf("请先初始化迷宫!\n");printf("\n所设置入口坐标为(%d,%d),出口坐标为(%d,%d).\n",start.row,start.line,end.row,end.line);break;case 3://输出此迷宫通路路径if(aa==2){aa=3;if(MazePath(maze,S,start,end)) //若有通路,显示通路printpath(maze,S,x,y,start,end);elseprintf("\n抱歉,找不到通路!\n\n");}elseprintf("请先初始化迷宫并寻找路径!\n");break;case 4:exit(0);break;default:exit(0);}}while(1);}/*若迷宫maze中从入口start到出口end的通道,则求得一条存放在栈中*/Status MazePath(int maze[12][12],SqStack &S, PosType start, PosType end){PosType curpos;int curstep;SElemType e;InitStack(S);curpos = start; // 设定"当前位置"为"入口位置curstep = 1; // 探索第一步do {if (Pass(maze,curpos)) // 当前位置可通过,即是未曾走到过的通道块{Markfoot(maze,curpos); // 留下足迹e.di =1;e.ord = curstep;e.seat= curpos;Push(S,e); // 加入路径if (curpos.row==end.row && curpos.line==end.line)return OK; // 到达终点(出口)curpos = NextPos(curpos, 1); // 下一位置是当前位置的东邻curstep++; // 探索下一步}else // 当前位置不能通过{if (!StackEmpty(S)){Pop(S,e);while (e.di==4 && !StackEmpty(S)){Markfoot(maze,e.seat); // 留下不能通过的标记,并退回一步Pop(S,e);}if (e.di<4){e.di++; // 换下一个方向探索Push(S, e);curpos = NextPos(e.seat, e.di); // 当前位置设为新方向的相邻块}}}} while (!StackEmpty(S));return ERROR;}/*初始化迷宫时间复杂度:n^2*/void Initmaze(int maze[12][12],int x,int y){char select;do{printf("创建方式A:自动生成B:手动创建\n");label: scanf("%c",&select);if(select=='a'||select=='A') //自动生成{for(int i=1;i<x+1;i++){for(int j=1;j<y+1;j++)maze[i][j]=rand()%2;}break;}else if(select=='b'||select=='B') //手动设置{printf("按行输入%d*%d数据,0代表可通,1代表不可通(每行以Enter结束):\n",x,y);for(int i=1;i<x+1;i++){for(int j=1;j<y+1;j++)scanf("%d",&maze[i][j]);maze[i][y+1]=1;}for(i=0;i<x+2;i++)maze[x+1][i]=1;break;}else if(select=='\n')goto label; //排除Enter键的影响elseif(select!='b'||select!='B'||select!='a'||select!='A')printf("输入错误!\n");}while(select!='b'||select!='B'||select!='a'||select!='A');}/*显示迷宫时间复杂度:n^2*/void printmaze(int maze[12][12],int x,int y){printf("\n\n");printf("显示所建的迷宫(#表示墙):\n");printf("%c ",'#');printf("%c ",'y');for(int j=1;j<y+1;j++)printf("%d ",j);printf("%c ",'#');printf("\nx ");for(int i=1;i<y+3;i++)printf("%c ",'#');printf("\n");for(i=1;i<x+1;i++){if(i<x+1)printf("%d ",i);elseprintf("%c ",'#');printf("%c ",'#');for(int j=1;j<y+1;j++){printf("%d ",maze[i][j]);}printf("%c",'#');printf("\n");}for(i=0;i<y+3;i++)printf("%c ",'#');printf("\n");}/*输出路径时间复杂度:n^2*/void printpath(int maze[12][12],SqStack S,int x,int y,PosType start,PosType end) {printf("\n\n\001通路路径:\n");SElemType * p=S.base;while(p!=S.top){maze[p->seat.row][p->seat.line]=2; //标记为路径中的点p++;}printf("\001路径图为:\n");printf("%c ",'#');printf("%c ",'y');for(int j=1;j<y+1;j++)printf("%d ",j);printf("%c ",'#');printf("\nx ");for(int m=1;m<y+3;m++)printf("%c ",'#');printf("\n");for(int i=1;i<x+1;i++){if(i<x+1)printf("%d ",i);elseprintf("%c ",'#');printf("%c ",'#');for(int j=1;j<y+1;j++){if(maze[i][j]==2){if(i==start.row&&j==start.line||i==end.row&&j==end.line){if(i==start.row&&j==start.line)printf("i ");if(i==end.row&&j==end.line)printf("o ");}elseprintf("%c ",' ');}elseprintf("%c ",'#');}printf("%c ",'#');printf("\n");}for(i=0;i<y+3;i++)printf("%c ",'#');printf("\n\n");printf("\001路径线路为:\n");SqStack M;InitStack(M);SElemType a;while (!StackEmpty(S)){Pop(S,a);Push(M,a);}while (!StackEmpty(M)){Pop(M,a);printf("(%d,%d)",a.seat.row,a.seat.line);}printf("\n");printf("路径输出成功!\n");}/* 判断当前位置是否可通*/Status Pass(int maze[12][12],PosType CurPos){if(maze[CurPos.row][CurPos.line]==0)return OK; // 如果当前位置是可以通过,返回1 elsereturn ERROR; // 其它情况返回0}/* 标记当前位置不可通*/void Markfoot(int maze[12][12],PosType CurPos){maze[CurPos.row][CurPos.line]=1;}/*进入下一位置*/PosType NextPos(PosType CurPos, int Dir){PosType ReturnPos;switch (Dir){case 1:ReturnPos.row=CurPos.row;ReturnPos.line=CurPos.line+1;break;case 2:ReturnPos.row=CurPos.row+1;ReturnPos.line=CurPos.line;break;case 3:ReturnPos.row=CurPos.row;ReturnPos.line=CurPos.line-1;break;case 4:ReturnPos.row=CurPos.row-1;ReturnPos.line=CurPos.line;break;}return ReturnPos;}/*创建一个空栈S*/Status InitStack(SqStack &S){S.base=(SElemType *)malloc(100*sizeof(SElemType));if(!S.base)return ERROR;S.top=S.base;S.stacksize=100;return OK;}/*插入新元素a*/Status Push(SqStack &S,SElemType &a){*S.top++=a;return OK;}/* 删除栈顶元素,a返回其值*/Status Pop(SqStack &S,SElemType &a){if(S.top==S.base)return ERROR;a=*--S.top;return OK;}/*检查是否空栈*/Status StackEmpty(SqStack S){if(S.top==S.base)return OK;return ERROR;}。

用c语言实现迷宫求解完美源代码

用c语言实现迷宫求解完美源代码

优先队列:用于存储待扩展节点,按照 f(n)值从小到大排序
A*搜索算法的C语言实现
算法流程:包括初始化、搜索、更新父节点等步骤 数据结构:使用优先队列来存储待搜索节点和已访问节点 实现细节:包括如何计算启发式函数、如何选择下一个节点等 性能优化:可以采用多线程、缓存等技术来提高算法的效率
A*搜索算法在迷宫求解中的应用
C语言实现A*搜 索算法
A*搜索算法的基本原理
定义:A*搜索算法是一种启发式搜索 算法,结合了最佳优先搜索和Dijkstra 算法的优点
基本思想:使用启发函数来评估节点的 重要性,优先选择最有希望的节点进行 扩展,从而有效地缩小搜索范围
关键参数:g(n):从起点经过节点n的 实际代价;h(n):从n到目标的估计代 价(启发式函数);f(n)=g(n)+h(n)
最短路径搜索
优化技巧:为了 提高搜索效率和 精度,可以采用 一些优化技巧, 如限制搜索范围、 使用优先队列等
C语言实现 Dijkstra算法
Dijkstra算法的基本原理
Dijkstra算法是一种用于求解最短路径问题的贪心算法 该算法通过不断选择当前最短路径的节点来逼近最短路径 Dijkstra算法适用于带权重的图,其中权重表示节点之间的距离 Dijkstra算法的时间复杂度为O((V+E)logV),其中V是节点数,E是边数
算法复杂度分析:时间复杂 度和空间复杂度分析
感谢您的观看
汇报人:XX
迷宫求解算法的C语言实现流程
初始化迷宫和路径
定义四个方向的移动方向
遍历迷宫,找到起点和终点
使用深度优先搜索或广度优先 搜索算法求解路径
C语言实现深度 优先搜索算法
深度优先搜索算法的基本原理

迷宫源代码

迷宫源代码

#include <windows.h>#include <stdlib.h>#include <iostream>#include <string>#include <list>#include <stack>#include <time.h>using namespace std;//class:MazePos-----------------------------------------//迷宫通道块类型class MazePos{public:int wx,ly; //块的X,Y坐标int path; //块的类型;0:空块,-1:墙壁,1:出口路径bool pass; //是否曾经过(对墙壁无意义);false:没有,true:曾经过 bool operator==(const MazePos pos){return (wx==pos.wx && ly==pos.ly );};MazePos operator=(const MazePos pos){wx=pos.wx;ly=pos.ly;pass=pos.pass;path=pos.path;return *this;};};//End:MazePos---------------------------------------//class:SElemType----------------------------------------- //辅助栈元素类型class SElemType{public:int ord; //迷宫通道块路径上的序号MazePos seat; //通道块在迷宫中的位置坐标int di; //从此通道块走向下一通道块的方向//0:无效,1:东,2:南,3:西,4:北bool operator==(const SElemType et){return (seat==et.seat);};SElemType operator=(const SElemType et){ord =et.ord ;seat =et.seat ;di =et.di ;return (*this);};};//End:SElemType--------------------------------------//struct:MazeMap-------------------------------------//由通道块组成的迷宫地图#define MAPWIDTH 10#define MAPHEIGHT 10typedef struct MazeMap{//由通道块矩阵构成MazePos mazemap[MAPWIDTH][MAPHEIGHT];}MazeMap;//End:MazeMap---------------------------------------//struct::MazeWay----------------------------------------//辅助出口路径链表元素类型typedef struct MazeWay{int wx,ly;}MazeWay;//End:MazeWay--------------------------------------------//Class:Maze----------------------------------------//主体类,迷宫路径问题求解class Maze{public:Maze(int width=MAPWIDTH,int height=MAPHEIGHT); //生成迷宫地图~Maze();void DoMaze(); //找出出口路径并显示private:bool InitOK; //初始化成功标志MazeMap map; //迷宫地图MazePos start,end; //迷宫的入口和出口bool FindPath(); //主要函数,寻找出口路径list<MazeWay> mazeway; //存放出口路径的临时链表void RandMap(); //随机生成迷宫地图函数bool CreateMap(bool init); //在初始和找到出口路径后生成相应地图函数bool pass(MazePos curpos); //当前路径通道块是否可通(即是不是未经过的空块)MazePos NextPos(MazePos curpos,int di); //取得当前通道块当前方向上的下一个通道块 bool Invalide(SElemType e); //使当前通道块标记为不可通void DisplayMaze(); //显示迷宫地图};Maze::Maze(int width,int height){////随机生成迷宫地图CreateMap(true);//显示地图DisplayMaze();}Maze::~Maze(){//Add codes here}bool Maze::FindPath (){////寻找出口,并生成出口路径链表if(InitOK){//MazeStack mstack;stack<SElemType,list<SElemType> > mstack;MazePos curpos=start;int curstep=1; //经过的步数MazeWay mw; //出口路径块元素unsigned mwsize=mazeway.size (); //为显示运行过程而设do{if(pass(curpos)){//如果当前位置可通(即是未走过的空块)//封装栈元素,将当前位置进栈SElemType e;e.ord =curstep;e.seat =curpos;e.di =1;mstack.push (e);//保存当前位置到出口路径链表mw.wx =e.seat .wx ;mw.ly =e.seat .ly ;mazeway.push_back (mw);//如果是出口,则结束if(curpos==end)return true;//不然就将得到下一个通道块curpos=NextPos(curpos,e.di );curstep++;}else{//当前位置不可通,则在栈内找到下一个位置if(!mstack.empty()){SElemType e;e=mstack.top ();mstack.pop ();//调整出口路径链表mazeway.pop_back ();while((e.di==0 || e.di ==4) && !mstack.empty ()) {Invalide(e); //标记刻通道块不能通过e=mstack.top ();mstack.pop (); //退回一步//调整出口路径链表mazeway.pop_back ();}if(mstack.empty ())return false;else if( e.di<5){e.di++;e.di=e.di%5;mstack.push (e);//保存当前位置到出口路径链表mw.wx =e.seat .wx ;mw.ly =e.seat .ly ;mazeway.push_back (mw);curpos=NextPos(e.seat ,e.di );}}}///*//显示运行过程if(mwsize!=mazeway.size () ){CreateMap(false);DisplayMaze();mwsize=mazeway.size ();Sleep(800); //要包含windows.h头文件}//*}while(!mstack.empty ());}return false;}MazePos Maze::NextPos(MazePos curpos,int di) {//MazePos pos;switch(di){case 1:pos=map.mazemap [curpos.wx+1][curpos.ly ] ;break;case 2:pos=map.mazemap [curpos.wx][curpos.ly+1 ] ;break;case 3:pos=map.mazemap [curpos.wx-1][curpos.ly] ;break;case 4:pos=map.mazemap [curpos.wx][curpos.ly-1] ;break;}return pos;}bool Maze::pass(MazePos curpos){////通过MazePos类型参数传递的信息检查MazeMap map;if(curpos.wx <0 ||curpos.wx >=MAPWIDTH ||curpos.ly <0 ||curpos.ly >=MAPHEIGHT)return false;return (map.mazemap [curpos.wx ][curpos.ly ].path ==0 && map.mazemap [curpos.wx ][curpos.ly ].pass ==false );}void Maze::DoMaze (){//if(!InitOK)return;if(FindPath()){CreateMap(false);DisplayMaze();}else{cout<<endl<<"NO PATH!"<<endl;}}void Maze::RandMap (){////只能生成从左上到右下的迷宫地图MazeWay curway; //随机生成的当前正处理的出口路径块(组成mw) list<MazeWay> mw; //随机生成的出口路径(由curway组成)list<MazeWay>::iterator iter; //容器适配器curway.wx =0;curway.ly =1;mw.push_back (curway);curway.wx ++;mw.push_back (curway);srand(time(0)); //取得当前时间作为随机数种子while(curway.wx <MAPWIDTH-1 && curway.ly <MAPHEIGHT-1){if(rand()%2==1){//生成随机X坐标上的路径块curway.wx ++;mw.push_back (curway);}else{//生成随机Y坐标上的路径块curway.ly ++;mw.push_back (curway);}}srand(time(0));for(int y=0;y<MAPHEIGHT;y++){for(int x=0;x<MAPWIDTH;x++){//填充每个通道块map.mazemap [x][y].wx =x;map.mazemap [x][y].ly =y;map.mazemap [x][y].pass =false;if(x==0||y==0||x==MAPWIDTH-1||y==MAPHEIGHT-1){//生成四周墙壁map.mazemap [x][y].path =-1;//map.mazemap [x][y].pass =true;}else{if(rand()%10>=6) //数值越小,墙壁越多{map.mazemap [x][y].path =-1; //随机生成墙壁//map.mazemap [x][y].pass =true;}else{map.mazemap [x][y].path =0; //生成空的通道块//map.mazemap [x][y].pass =false;}}}}//生成出口路径for(iter=mw.begin ();iter!=mw.end ();iter++){map.mazemap [(*iter).wx ][(*iter).ly ].path =0;//map.mazemap [(*iter).wx ][(*iter).ly ].pass =false; }//生成入口和出口start=map.mazemap [mw.front ().wx][mw.front ().ly];end=map.mazemap [mw.back ().wx][mw.back ().ly];//初始化成功InitOK=true;}bool Maze::CreateMap (bool init){//if(init){RandMap();}else{for(int y=0;y<MAPHEIGHT;y++)for(int x=0;x<MAPWIDTH;x++){if(map.mazemap [x][y].path ==0)map.mazemap [x][y].pass =0;}list<MazeWay>::iterator iter;for(iter=mazeway.begin ();iter!=mazeway.end ();iter++) {map.mazemap [(*iter).wx][(*iter).ly ].path =1;}}return true;}bool Maze::Invalide (SElemType e){////通过SElemType类型参数传递的信息修正MazeMap map;if(e.seat .wx<0 ||e.seat .wx>=MAPWIDTH ||e.seat .ly<0 ||e.seat .ly>=MAPHEIGHT)return false;map.mazemap [e.seat .wx][e.seat .ly ].pass =true;return true;}void Maze::DisplayMaze (){//cout<<endl;for(int y=0;y<MAPHEIGHT;y++){for(int x=0;x<MAPWIDTH;x++){switch (map.mazemap [x][y].path){case -1:cout<<"█";break; //墙壁图案case 0:cout<<" ";break; //空块图案case 1:cout<<"==";break; //出口路径图案}}cout<<endl;}cout<<endl;}//End:Maze----------------------------------------//main-------------------------------------------- //主函数,迷宫求解演示int main(int argc, char* argv[]){//cout<<"下面是随机生成的迷宫:"<<endl;Maze mymaze; //生成迷宫cout<<"按任意键演示迷宫解法!"<<endl;system("pause");mymaze.DoMaze (); //生成出口路径cout<<"演示结束."<<endl;system("pause");return 0;}。

数据结构迷宫源代码

数据结构迷宫源代码

数据结构迷宫源代码```python数据结构迷宫源代码概述本文档介绍了一个基于数据结构的迷宫算法的源代码。

迷宫是一个由墙壁和通道组成的网络结构,本算法通过使用数据结构来并解决迷宫。

目录1、算法原理1.1 数据结构选择1.2 迷宫1.3 解决迷宫2、源代码实现2.1 数据结构定义2.2 迷宫算法2.3 迷宫解决算法3、使用示例4、附件1、算法原理1.1 数据结构选择本算法使用了图的数据结构来表示迷宫,其中节点表示迷宫中的位置,边表示相邻位置之间的连接。

使用图的数据结构可以方便地和解决迷宫。

1.2 迷宫迷宫的算法采用了深度优先搜索(DFS),通过递归地寻找迷宫中的通道并打通墙壁,直到无法再继续搜索。

迷宫的过程中使用了堆栈来辅助处理。

1.3 解决迷宫解决迷宫的算法采用了广度优先搜索(BFS),通过从起点开始,逐步扩展搜索范围,直到找到终点或无法再继续搜索。

解决迷宫的过程中使用了队列来辅助处理。

2、源代码实现2.1 数据结构定义以下是迷宫和解决算法所使用的数据结构的定义。

```python定义迷宫节点class MazeNode:def __init__(self, x, y):self:x = xself:y = yself:visited = Falseself:walls = {'N': True, 'S': True, 'W': True, 'E': True}定义迷宫class Maze:def __init__(self, width, height):self:width = widthself:height = heightself:nodes = [[MazeNode(x, y) for y inrange(height)] for x in range(width)]```2.2 迷宫算法以下是迷宫的算法的实现。

```pythondef generate_maze(maze):start_node = maze:nodes[0][0]stack = [(start_node, None)]while stack:curr_node, prev_node = stack:pop()if not curr_node:visited:curr_node:visited = Trueif prev_node:remove_wall(prev_node, curr_node)neighbors =get_unvisited_neighbors(curr_node)if neighbors:stack:append((curr_node, prev_node)) next_node = random:choice(neighbors) stack:append((next_node, curr_node))```2.3 迷宫解决算法以下是解决迷宫的算法的实现。

C语言数据结构之迷宫问题

C语言数据结构之迷宫问题

C语⾔数据结构之迷宫问题本⽂实例为⼤家分享了数据结构c语⾔版迷宫问题栈实现的具体代码,供⼤家参考,具体内容如下程序主要参考⾃严蔚敏⽼师的数据结构c语⾔版,在书中程序的⼤体框架下进⾏了完善。

关于迷宫问题的思路可查阅原书。

#include<iostream>using namespace std;#define MAXSIZE 10typedef int Status;typedef struct{int x;int y;}Postype;typedef struct{int ord;Postype seat;int dir;}SElemType;//栈的元素类型typedef struct{//SElemType data[MAXSIZE];SElemType* top;SElemType* base;}Stack;//栈的结构类型typedef struct{char arr[MAXSIZE][MAXSIZE];}MAZETYPE;//迷宫结构体MAZETYPE maze;void InitMaze(){maze.arr[0][0] = maze.arr[0][1] = maze.arr[0][2] = maze.arr[0][3] = maze.arr[0][4] = maze.arr[0][5] = maze.arr[0][6] = maze.arr[0][7] = maze.arr[0][8] = maze.arr[0][9] = '1'; maze.arr[1][0] = maze.arr[1][3] = maze.arr[1][7] = maze.arr[1][9] = '1';maze.arr[1][1] = maze.arr[1][2] = maze.arr[1][4] = maze.arr[1][5] = maze.arr[1][6] = maze.arr[1][8] = '0';maze.arr[2][0] = maze.arr[2][3] = maze.arr[2][7] = maze.arr[2][9] = '1';maze.arr[2][1] = maze.arr[2][2] = maze.arr[2][4] = maze.arr[2][5] = maze.arr[2][6] = maze.arr[2][8] = '0';maze.arr[3][0] = maze.arr[3][5] = maze.arr[3][6] = maze.arr[3][9] = '1';maze.arr[3][1] = maze.arr[3][2] = maze.arr[3][3] = maze.arr[3][4] = maze.arr[3][7] = maze.arr[3][8] = '0';maze.arr[4][0] = maze.arr[4][2] = maze.arr[4][3] = maze.arr[4][4] = maze.arr[4][9] = '1';maze.arr[4][1] = maze.arr[4][5] = maze.arr[4][6] = maze.arr[4][7] = maze.arr[4][8] = '0';maze.arr[5][0] = maze.arr[5][4] = maze.arr[5][9] = '1';maze.arr[5][1] = maze.arr[5][2] = maze.arr[5][3] = maze.arr[5][5] = maze.arr[5][6] = maze.arr[5][7] = maze.arr[5][8] = '0';maze.arr[6][0] = maze.arr[6][2] = maze.arr[6][6] = maze.arr[6][9] = '1';maze.arr[6][1] = maze.arr[6][3] = maze.arr[6][4] = maze.arr[6][5] = maze.arr[6][7] = maze.arr[6][8] = '0';maze.arr[7][0] = maze.arr[7][2] = maze.arr[7][3] = maze.arr[7][4] = maze.arr[7][6] = maze.arr[7][9] = '1';maze.arr[7][1] = maze.arr[7][5] = maze.arr[7][7] = maze.arr[7][8] = '0';maze.arr[8][0] = maze.arr[8][1] = maze.arr[8][9] = '0';maze.arr[8][2] = maze.arr[8][3] = maze.arr[8][4] = maze.arr[8][5] = maze.arr[8][6] = maze.arr[8][7] = maze.arr[8][8] = '0';maze.arr[9][0] = maze.arr[9][1] = maze.arr[9][2] = maze.arr[9][3] = maze.arr[9][4] = maze.arr[9][5] = maze.arr[9][6] = maze.arr[9][7] = maze.arr[9][8] = maze.arr[9][9] = '1'; }Status initStack(Stack &s){s.base = (SElemType*)malloc(MAXSIZE*sizeof(SElemType));if (!s.base) return 0;s.top = s.base;return 1;}void Push(Stack &s, SElemType e){*s.top++ = e;}void Pop(Stack &s, SElemType &e){e = *--s.top;}Status StackEmpty(Stack &s){if (s.top == s.base) return 1;else return 0;}Status Pass(Postype curpos){if (maze.arr[curpos.x][curpos.y] == '0')return 1;else return 0;}void Foot(Postype curpos){maze.arr[curpos.x][curpos.y] = '*';}void MarkPrint(Postype curpos){maze.arr[curpos.x][curpos.y] = '!';}Status StructCmp(Postype a, Postype b){if (a.x = b.x&&a.y == b.y) return 1;else return 0;}//下⼀个位置Postype NextPos(Postype CurPos, int Dir){Postype ReturnPos;switch (Dir){case 1:ReturnPos.x = CurPos.x;ReturnPos.y = CurPos.y + 1;break;case 2:ReturnPos.x = CurPos.x + 1;ReturnPos.y = CurPos.y;break;case 3:ReturnPos.x = CurPos.x;ReturnPos.y = CurPos.y - 1;break;case 4:ReturnPos.x = CurPos.x - 1;ReturnPos.y = CurPos.y;break;}return ReturnPos;}Status MazePath(Postype start, Postype end) {Stack s;SElemType e;initStack(s);Postype curpos = start;int curstep = 1;do{if (Pass(curpos)){Foot(curpos);e = { curstep, curpos, 1 };Push(s, e);if (StructCmp(curpos, end)) return 1;curpos = NextPos(curpos, 1);curstep++;}else{if (!StackEmpty(s)){Pop(s, e);while (e.dir ==4 &&!StackEmpty(s)){MarkPrint(e.seat); Pop(s, e);}if (e.dir < 4 && !StackEmpty(s)){e.dir++;Push(s, e);curpos = NextPos(e.seat, e.dir);}}}} while (!StackEmpty(s));return 0;}int main(){InitMaze();Postype s, e;s.x = s.y = 1;e.x = e.y = 8;if (MazePath(s, e))printf("迷宫成功解密!\n");elseprintf("解密失败\n");for (int i = 0; i < 10; i++){for (int j = 0; j < 10; j++){printf("%c ", maze.arr[i][j]);}printf("\n");}cout << "-=================================" << endl;for (int i = 0; i < 10; i++){for (int j = 0; j < 10; j++){if (maze.arr[i][j] == '*' || maze.arr[i][j] == '!')printf("%c ", maze.arr[i][j]);else cout << " ";}printf("\n");}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

数据结构 迷宫

数据结构  迷宫

数据结构迷宫程序代码:#include<stdio.h>#include<stdlib.h>#include<time.h> //用于设定随机数种子#include<conio.h>#define OK 1#define ERROR 0#define OVERFLOW -2#define N 24typedef struct //定义线性表的结构{int ord; //判断该位置是否可通(0表示不通,1表示通)(墙—█入口—⊙出口—㊣)int seat; //判断从上一个位置到该位置的方向(东→南↓西←北↑)int pass; //判断该位置是否走过(0表示没有走过,1表示走过)}SElemType;typedef struct{SElemType *elem;}List;typedef struct //定义栈的结构{int loc; //记录对应线性表中元素的位置int seat; //判断从上一个位置到该位置的方向(东→南↓西←北↑)int di; //表示从此通道走向下一通道块的方向}Element;typedef struct{Element *base;Element *top;int num;}Stack;int w=0,Flag=0,n;SElemType *InitList();int MazePath1(List maze1,Stack &maze2);int MazePath2(List maze1,Stack &maze2);int InitList(List &maze1);void InitStack(Stack &maze2);int search(int mark,int n);void Output1(List maze1);void Output2(List maze1,Stack maze2);void main(){int i,a=1,b,c;List maze1;Stack maze2;InitStack(maze2);while(a){for(i=0;i<4;i++){InitList(maze1);if(i!=0)printf("\n\n\n\n");Output1(maze1);if(w==0){printf("\n\n\n\n\n\n\n\n\t\t1——计算机走迷宫\t \t2——人走迷宫");printf("\n");scanf("%d",&b);}getchar();if(b==1){system("cls");c=MazePath1(maze1,maze2);if(c==0)break;system("cls");Output2(maze1,maze2);maze2.top=maze2.base;}else if(b==2){system("cls");c=MazePath2(maze1,maze2);if(c==0)break;system("cls");Output2(maze1,maze2);maze2.top=maze2.base;}elseprintf("你的输入有误,请重新输入:");}system("cls");printf("\n\n\n\n\n\n\n你是否想进入下一个迷宫\n\n\n\n\t\t\t\t1——是\t\t0——否\n");scanf("%d",&a);system("cls");Flag=0;}}int InitList(List &maze1){int a,b=0,i,j;static int k=0,t=0;srand((unsigned)time(NULL)); //用于改变随机数if(Flag==1) //用于判断路径{for(i=0;i<n;i++)for(j=0;j<n;j++){maze1.elem[i*n+j].seat=0;maze1.elem[i*n+j].pass=0;}Flag=0;return OK;}if(k==0) //初始化线性表{maze1.elem=(SElemType *)malloc((N*N)*sizeof(SElemType));if(!maze1.elem)exit(OVERFLOW);}if(w==4){w=0;t=0;k=0;}if(t==0){while(1) //选择迷宫的大小{printf("请选择迷宫的大小(4~24):");scanf("%d",&n);if(n>3&&n<25)break;else{system("cls");printf("你选择的迷宫大小有误,请重新输入\n\n");}}for(i=0;i<n*n;i++) //随机产生迷宫{a=rand()%2;maze1.elem[i].ord=a;}printf("\n\n\n");for(i=0;i<n*n;) //用于避免产生太多死迷宫{do{b=rand()%4;}while(!b);maze1.elem[i].ord=1;i=i+b;}for(i=0;i<n;i++) //设定迷宫的外围{maze1.elem[n*n-n+i].ord=maze1.elem[i].ord=0;maze1.elem[i*n].ord=maze1.elem[i*n+n-1].ord=0;}t++;}for(i=0;i<n;i++) //每走一步后进行初始化{for(j=0;j<n;j++){maze1.elem[i*n+j].seat=0; //只将线性表的判断方向的变量进行初始化if(k==0){maze1.elem[i*n+j].pass=0;maze1.elem[n+1].ord=2;maze1.elem[n*n-n-2].ord=3;if(maze1.elem[n+2].ord==0&&maze1.elem[2*n+1].ord==0)maze1.elem[2*n+1].ord=1;k++;}}}return OK;}int MazePath1(List maze1,Stack &maze2){int a=0;Element e;maze2.num=0;e.loc=n+1; //设定入口e.seat=20;e.di=1;maze1.elem[n+1].pass=1;*maze2.top++=e;while(a!=(n*n-n-2)) //判断是否到终点{while(1){while(1){a=search(e.loc,e.di); //根据地址和方向确定下一个位置的地址if(maze1.elem[a].pass==1||maze1.elem[a].ord==0) //判断是否走过和能否可通,否则换一个方向e.di++;elsebreak;if(e.di>4) //如果此处的四个方向都不可通,则结束break;}if(e.di>4) //若某处的四个方向都不可通吗,则将此元素出栈{maze2.top--;if(maze2.top==maze2.base) //判断迷宫是否可通{Output2(maze1,maze2);printf("\n\n\n\t\t\t此迷宫不能通行,欢迎进入下一个迷宫\n\n\n");printf("\n\n\n\t\t\t\t 按Enter→\n\n\n\n\n\n\n");getchar();w=4;return ERROR;}e=*(maze2.top-1);e.di++;maze2.num++; //记录所走步数Output2(maze1,maze2);getchar();system("cls");}elsebreak;}e.loc=a; //将元素入栈e.seat=e.di+w;if(e.di==3) //判断此元素的下一个方向e.di=2;elsee.di=1;maze1.elem[a].pass=1;*maze2.top++=e;maze2.num++;Output2(maze1,maze2); //将迷宫模型输出getchar();system("cls");}w++;Flag=1; //用于标识一次路径结束return OK;}int MazePath2(List maze1,Stack &maze2){int a=0;char r;Element e;maze2.num=0;e.loc=n+1;e.seat=20;*maze2.top++=e;system("cls");printf("请选择方向:");printf("\n\nW——↑\t\tS——↓\t\tA——←\t\tD——→\t\tN——迷宫不可通");printf("\n\n");Output1(maze1);printf("\n\n\n\n\n\n\t\t\t\t 按Enter→\n\n\n\n\n\n\n");getchar();system("cls");printf("\n\n\n\n");Output1(maze1);while(a!=(n*n-n-2)){while(1){flushall();r=getche();flushall();if(r=='W'||r=='w')e.di=4;else if(r=='S'||r=='s')e.di=2;else if(r=='A'||r=='a')e.di=3;else if(r=='D'||r=='d')e.di=1;else if(r=='N'||r=='n'){printf("\n\n\n\t\t\t此迷宫不能通行,欢迎进入下一个迷宫\n\n\n");printf("\n\n\n\t\t\t\t 按Enter→\n\n\n\n\n\n\n");getchar();w=4;return ERROR;}else{printf("\n\n\n\n\n\n你输入的方向错误,请重新输入:");continue;}a=search(e.loc,e.di);if(maze1.elem[a].ord==0){system("cls");Output2(maze1,maze2);printf("\n\n\n\n\n\n此方向不可通,请重新输入:");}elsebreak;}if(abs(e.di-e.seat)==2&&e.seat<5){maze2.top--;e=*(maze2.top-1);maze2.num++;system("cls");Output2(maze1,maze2);}else{(maze2.top-1)->di=e.di;e.loc=a;e.seat=e.di;*maze2.top++=e;maze2.num++;system("cls");Output2(maze1,maze2);}}w=4;Flag=1;return OK;}void InitStack(Stack &maze2) //对栈进行初始化{maze2.base=(Element *)malloc((N*N)*sizeof(Element));if(!maze2.base)exit(OVERFLOW);maze2.top=maze2.base;}int search(int mark,int m) //通过地址和方向取得相应的地址值{int a,i=w+1;switch(i){case 1:break;case 2:m=m+1;break;case 3:m=m+2;break;case 4:m=m+3;break;}if(m%4==1)a=mark+1;else if(m%4==2)a=mark+n;else if(m%4==3)a=mark-1;elsea=mark-n;return a;}void Output1(List maze1) //输出迷宫的初始模型{int i;printf("\n\n\n\n");for(i=0;i<n*n;i++){if(i%n==0){if(n<14)printf("\n\t\t\t\t");elseprintf("\n\t\t\t");}if(maze1.elem[i].ord==0)printf("█");else if(maze1.elem[i].ord==1)printf(" ");else if(maze1.elem[i].ord==2)printf("⊙");elseprintf("㊣");}}void Output2(List maze1,Stack maze2) //输出迷宫的路径{int i,j;static int k=1;if(w==0)k=1;Element e;j=maze2.top-maze2.base-1;while(maze2.base!=maze2.top) //将栈的元素赋值给线性表{e=*--maze2.top;maze1.elem[e.loc].seat=e.seat;}maze1.elem[n+1].seat=20;maze1.elem[n*n-n-2].seat=30;//对入口和出口进行处理printf("\n\n\n\n\n\n\n\n");for(i=0;i<n*n;i++){if(i%n==0){if(n<14)printf("\n\t\t\t\t");elseprintf("\n\t\t\t");}if(maze1.elem[i].ord==0)printf("█");else{ if(maze1.elem[i].seat==20)printf("⊙");else if(maze1.elem[i].seat==30)printf("㊣");else{if(maze1.elem[i].seat%4==1)printf("→");else if(maze1.elem[i].seat%4==2)printf("↓");else if(maze1.elem[i].seat%4==3)printf("←");else if(maze1.elem[i].seat==4)printf("↑");elseprintf(" ");}}}printf("\n\n");if(Flag==1) //输出迷宫的总步骤和所需步骤{printf("\n\n\t\t\t 路径%d共走%d步,所需步骤为%d步",k,maze2.num,j);if(w==4)printf("\n\n\n\t\t\t此迷宫已结束,欢迎进入下一个迷宫\n\n\n");printf("\n\n\n\n\t\t\t\t 按Enter→\n\n\n\n\n\n\n");getchar();system("cls");k++;}InitList(maze1); //输出后再对线性表进行初始化}程序运行结果:计算机走迷宫:注:每个迷宫都走四次,分别向东、南、西、北四个方向走迷宫,并计算出走到终点所走的步骤;每走一步按Enter键。

数据结构编程《迷宫问题》

数据结构编程《迷宫问题》
} if(arr[cur.x][cur.y+1]==0) //南 {
Point t; t.x =cur.x; t.y=cur.y+1; if(next(arr,t,end)) return 1;
} … //西 …//北 arr[cur.x][cur.y] = 1; return 0; }
3.非递归 算法
else if (arr[P.x-1][P.y]==0) arr[--P.x][P.y] = 2;
else
{
P = PointStack.Pop();
arr[P.x][P.y] = 1;
P = PointStack.Pop();
}
辅助函数
单击此处可添加副标题
//打印迷宫 void PrintPath(int arr[][10]) { for (int i=0;i<10;i++) { for (int j=0;j<10;j++) { if (arr[i][j]==-1) cout<<"■"; else if (arr[i][ j]==2) cout<<" *"; else cout<<"□"; } cout<<endl; } cout<<endl; }
迷宫求解
每走一步:
1. 如果当前位置=出口,结束 2. 否则:
① 假设当前位置为路径; ② 如果东面未走过:向东走一步 ③ 如果南面未走过:向南走一步 ④ 如果西面未走过:向西走一步 ⑤ 如果北面未走过:向北走一步 ⑥ 设置当前位置走不通,回溯
int next(int arr[][10],Point cur,Point end) {

数据结构迷宫源代码

数据结构迷宫源代码

#include <stdio.h>#include <malloc.h>#include <stdlib.h>#include <string.h>#include <time.h>#define OK 1#define ERROR 0#define NULL 0#define OVERFLOW -2#define STACK_INIT_SIZE 100#define STACKINCREMENT 10//栈的顺序存储表示typedef struct{int x; /*列*/int y; /*行*/}PosType; //坐标位置类型typedef struct{int ord; //通道块在路径上的序号PosType seat; //通道块在迷宫中的坐标位置int di; //从此通道块走向下一通道块的方向}SElemType; //栈的元素类型typedef struct {SElemType *base;SElemType *top;int stacksize; //当前已分配的存储空间,以元素为单位}SqStack;//基本操作int InitStack(SqStack *S){S->base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));if(!S->base)exit(OVERFLOW);S->top=S->base;S->stacksize=STACK_INIT_SIZE;return OK;}//若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR int GetTop(SqStack *S,SElemType *e){if(S->top==S->base) return ERROR;*e=*(S->top-1);return OK;}int Push(SqStack *S,SElemType *e)//插入元素e作为新的栈顶元素{if(S->top-S->base>=S->stacksize)/*栈满,追加存储空间*/{S->base = (SElemType *)realloc(S->base,(S->stacksize + STACKINCREMENT) * sizeof(SElemType));if(!S->base) exit(OVERFLOW);S->top=S->base+S->stacksize;S->stacksize+=STACKINCREMENT;}*S->top++=*e;return OK;}//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERRORint Pop(SqStack *S,SElemType *e){if(S->top==S->base) return ERROR;*e=*--S->top;return OK;}int StackEmpty(SqStack *S){return(S->top==S->base) ;}//迷宫程序typedef struct {int lie; /*列数*/int hang; /*行数*/char a[999][999];}MazeType; /*迷宫类型*//*随机生成迷宫*/int generatemaze( MazeType *maze){int i,j;maze->a[0][0]=2;maze->a[++maze->hang][++maze->lie]=3;/*设置外墙*/maze->a[0][maze->lie]='!';maze->a[maze->hang][0]='!';for(j=1;j<maze->lie;j++){maze->a[0][j]='!';maze->a[maze->hang][j]='!';}for(i=1;i<maze->hang;i++){maze->a[i][0]='!';maze->a[i][maze->lie]='!';}srand((unsigned)time( NULL ));rand();for(i=1; i <maze->hang; i++)for(j=1;j<maze->lie;j++){if (rand()>=RAND_MAX/4) maze->a[i][j] =' '; //' ' 暗示出路else maze->a[i][j] ='!'; //'!'暗示无出路}return OK;}int Pass(MazeType *maze, PosType curpos ) //判断当前位置可否通过{if ((curpos.x < 1) || (curpos.x >= maze->lie)) return ERROR;if ((curpos.y < 1) || (curpos.y >= maze->hang)) return ERROR;if (maze->a[curpos.y][curpos.x]==' ') return OK;else return ERROR;}int FootPrint(MazeType *maze,PosType curpos) //留下足迹{maze->a[curpos.y][curpos.x]='*';return OK;}int MarkPrint(MazeType *maze,PosType curpos) //留下不能通过的标记{maze->a[curpos.y][curpos.x]='@';return OK;}PosType NextPos(PosType curpos,int di) //返回当前位置的下一位置{PosType pos=curpos;switch(di){case 1: //右东pos.x++;break;case 2: //下南pos.y++;break;case 3: //左西pos.x--;break;case 4: //上北pos.y--;break;}return pos;}//若迷宫有解,则求得一条存放在栈中(从栈底到栈顶),并返回OK,否则返回ERROR int MazePath(MazeType *maze,PosType start,PosType end){PosType curpos;SqStack *S=(SqStack *)malloc(sizeof(SqStack));InitStack(S);SElemType *e;e=(SElemType *)malloc(sizeof(SElemType));curpos=start; //设定当前位置为入口位置int curstep = 1; //探索第一步do{if(Pass(maze,curpos)) //当前位置可通过{FootPrint(maze,curpos);e->ord=curstep;e->seat=curpos;e->di=1;Push(S,e);if(curpos.x==end.x&&curpos.y==end.y) return (OK);curpos=NextPos(curpos,1);curstep++;}else{if(!StackEmpty(S)){Pop(S,e);while(e->di==4&&!StackEmpty(S)) //栈不空但栈顶位置四周均不通{MarkPrint(maze,e->seat);Pop(S,e);}if(e->di<4) //栈不空且栈顶位置四周有其他位置未探索{e->di++;Push(S,e);curpos=e->seat;curpos=NextPos(curpos,e->di);}}}}while(!StackEmpty(S));return ERROR;}void PrintMaze(MazeType *maze) //打印迷宫{int i,j,k,n;int c[999],d[999];for(i=0,k=0;i<=maze->hang;i++){for(j=0;j<=maze->lie;j++){printf("%c ",maze->a[i][j]);if(maze->a[i][j]=='*'){c[k]=i;d[k]=j;k++;}}printf("\n");}n=k;for(k=0;k<n;k++)printf("<%d,%d>",c[k],d[k]);printf("\n");printf("\n");}int main(){int zmg;char ch;printf(" 数据结构课程设计--迷宫问题求解\n\n");printf(" |----------------------------------------|\n");printf(" | |\n");printf(" | |\n");printf(" | |\n");printf(" | |\n");printf(" | XXXX XXXXXXXXXXXXXX |\n");printf(" | XXXXXXX |\n");printf(" |----------------------------------------|\n");getchar();do{system("cls");fflush(stdin);MazeType *maze=(MazeType *)malloc(sizeof(MazeType));//设置迷宫的长宽不含外墙printf("请输入迷宫的列数(不含外墙时):");scanf("%d",&maze->lie);printf("请输入迷宫的行数(不含外墙时):");scanf("%d",&maze->hang);generatemaze(maze);printf("随机创建迷宫\n");PrintMaze(maze);getchar();getchar();PosType start,end;start.x=1;start.y=1;end.x=maze->lie-1;end.y=maze->hang-1;zmg=MazePath(maze,start,end);if(zmg){printf("此迷宫通路为\n");PrintMaze(maze);}else printf("此迷宫无通路\n");//getchar();printf("再次尝试?(Y/N)?");scanf("%c",&ch);}while(ch=='Y'||ch=='y');return 0; }。

C++迷宫游戏源代码

C++迷宫游戏源代码
for(int j=1;j<=n;j++){
if(maze[i][j]==-1)
maze[i][j]=0;
}
}
}
int path1(int **maze,int m,int n,int c,int d,int x1,int y1)//最短路径
{ //m,n为迷宫的ze为迷宫;
front++; //当前点搜索完,取下一个点搜索
} //while
G:cout<<"无路径。"<<endl;
return 0;
}
void path(int **maze,int a,int b,int m,int n)
{
item move[8]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
#include<iostream>
#include<stack>
#include<stdio.h>
#include<time.h>
#include<string>
using namespace std;
typedef struct
{
int x,y;
}item;
typedef struct
}
if(i==x1&&j==y1){
cout<<"最短路径为:"<<endl;
printpath(sq,rear); //输出路径;
restore(maze,m,n); //恢复迷宫;
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include <stdio.h>#include <malloc.h>#include <stdlib.h>#include <string.h>#include <time.h>#define OK 1#define ERROR 0#define NULL 0#define OVERFLOW -2#define STACK_INIT_SIZE 100#define STACKINCREMENT 10//栈的顺序存储表示typedef struct{int x; /*列*/int y; /*行*/}PosType; //坐标位置类型typedef struct{int ord; //通道块在路径上的序号PosType seat; //通道块在迷宫中的坐标位置int di; //从此通道块走向下一通道块的方向}SElemType; //栈的元素类型typedef struct {SElemType *base;SElemType *top;int stacksize; //当前已分配的存储空间,以元素为单位}SqStack;//基本操作int InitStack(SqStack *S){S->base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));if(!S->base)exit(OVERFLOW);S->top=S->base;S->stacksize=STACK_INIT_SIZE;return OK;}//若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR int GetTop(SqStack *S,SElemType *e){if(S->top==S->base) return ERROR;*e=*(S->top-1);return OK;}int Push(SqStack *S,SElemType *e)//插入元素e作为新的栈顶元素{if(S->top-S->base>=S->stacksize)/*栈满,追加存储空间*/{S->base = (SElemType *)realloc(S->base,(S->stacksize + STACKINCREMENT) * sizeof(SElemType));if(!S->base) exit(OVERFLOW);S->top=S->base+S->stacksize;S->stacksize+=STACKINCREMENT;}*S->top++=*e;return OK;}//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERRORint Pop(SqStack *S,SElemType *e){if(S->top==S->base) return ERROR;*e=*--S->top;return OK;}int StackEmpty(SqStack *S){return(S->top==S->base) ;}//迷宫程序typedef struct {int lie; /*列数*/int hang; /*行数*/char a[999][999];}MazeType; /*迷宫类型*//*随机生成迷宫*/int generatemaze( MazeType *maze){int i,j;maze->a[0][0]=2;maze->a[++maze->hang][++maze->lie]=3;/*设置外墙*/maze->a[0][maze->lie]='!';maze->a[maze->hang][0]='!';for(j=1;j<maze->lie;j++){maze->a[0][j]='!';maze->a[maze->hang][j]='!';}for(i=1;i<maze->hang;i++){maze->a[i][0]='!';maze->a[i][maze->lie]='!';}srand((unsigned)time( NULL ));rand();for(i=1; i <maze->hang; i++)for(j=1;j<maze->lie;j++){if (rand()>=RAND_MAX/4) maze->a[i][j] =' '; //' ' 暗示出路else maze->a[i][j] ='!'; //'!'暗示无出路}return OK;}int Pass(MazeType *maze, PosType curpos ) //判断当前位置可否通过{if ((curpos.x < 1) || (curpos.x >= maze->lie)) return ERROR;if ((curpos.y < 1) || (curpos.y >= maze->hang)) return ERROR;if (maze->a[curpos.y][curpos.x]==' ') return OK;else return ERROR;}int FootPrint(MazeType *maze,PosType curpos) //留下足迹{maze->a[curpos.y][curpos.x]='*';return OK;}int MarkPrint(MazeType *maze,PosType curpos) //留下不能通过的标记{maze->a[curpos.y][curpos.x]='@';return OK;}PosType NextPos(PosType curpos,int di) //返回当前位置的下一位置{PosType pos=curpos;switch(di){case 1: //右东pos.x++;break;case 2: //下南pos.y++;break;case 3: //左西pos.x--;break;case 4: //上北pos.y--;break;}return pos;}//若迷宫有解,则求得一条存放在栈中(从栈底到栈顶),并返回OK,否则返回ERROR int MazePath(MazeType *maze,PosType start,PosType end){PosType curpos;SqStack *S=(SqStack *)malloc(sizeof(SqStack));InitStack(S);SElemType *e;e=(SElemType *)malloc(sizeof(SElemType));curpos=start; //设定当前位置为入口位置int curstep = 1; //探索第一步do{if(Pass(maze,curpos)) //当前位置可通过{FootPrint(maze,curpos);e->ord=curstep;e->seat=curpos;e->di=1;Push(S,e);if(curpos.x==end.x&&curpos.y==end.y) return (OK);curpos=NextPos(curpos,1);curstep++;}else{if(!StackEmpty(S)){Pop(S,e);while(e->di==4&&!StackEmpty(S)) //栈不空但栈顶位置四周均不通{MarkPrint(maze,e->seat);Pop(S,e);}if(e->di<4) //栈不空且栈顶位置四周有其他位置未探索{e->di++;Push(S,e);curpos=e->seat;curpos=NextPos(curpos,e->di);}}}}while(!StackEmpty(S));return ERROR;}void PrintMaze(MazeType *maze) //打印迷宫{int i,j,k,n;int c[999],d[999];for(i=0,k=0;i<=maze->hang;i++){for(j=0;j<=maze->lie;j++){printf("%c ",maze->a[i][j]);if(maze->a[i][j]=='*'){c[k]=i;d[k]=j;k++;}}printf("\n");}n=k;for(k=0;k<n;k++)printf("<%d,%d>",c[k],d[k]);printf("\n");printf("\n");}int main(){int zmg;char ch;printf(" 数据结构课程设计--迷宫问题求解\n\n");printf(" |----------------------------------------|\n");printf(" | |\n");printf(" | |\n");printf(" | |\n");printf(" | |\n");printf(" | XXXX XXXXXXXXXXXXXX |\n");printf(" | XXXXXXX |\n");printf(" |----------------------------------------|\n");getchar();do{system("cls");fflush(stdin);MazeType *maze=(MazeType *)malloc(sizeof(MazeType));//设置迷宫的长宽不含外墙printf("请输入迷宫的列数(不含外墙时):");scanf("%d",&maze->lie);printf("请输入迷宫的行数(不含外墙时):");scanf("%d",&maze->hang);generatemaze(maze);printf("随机创建迷宫\n");PrintMaze(maze);getchar();getchar();PosType start,end;start.x=1;start.y=1;end.x=maze->lie-1;end.y=maze->hang-1;zmg=MazePath(maze,start,end);if(zmg){printf("此迷宫通路为\n");PrintMaze(maze);}else printf("此迷宫无通路\n");//getchar();printf("再次尝试?(Y/N)?");scanf("%c",&ch);}while(ch=='Y'||ch=='y');return 0; }。

相关文档
最新文档