求迷宫的最短路径 C语言代码

int x,y; // 行、列坐标 int pre; // 链域 }sqtype;
sqtype sq[r];
//作为队列的存储空间,记录被访问过的点
struct moved
{
int x,y;
// 坐标增量,取值-1,0,1
};
struct moved move[8]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
//
RESTORE(maze);
//恢复迷宫
return 1;
//成功,返回 1
}
}
front ++;
//出队,front 指向新的出发点
}
// 队空循环结束
return 0; //迷宫无路径,返回 0
}
void main() {
int i,j; printf("input the row,column: "); scanf("%d%d",&m,&n); for(i=0;i<m+2;i++)
int maze[m2][n2];
//迷宫数组
void PRINTPATH(sqtype sq[],int rear) {
int i=rear; do {
printf("\n(%d,%d)",sq[i].x,sq[i].y); i=sq[i].pre; }while(i!=0);
//打印输出最短路径
for(j=0;j<n+2;j++) if(i==0||i==m+1||j==0||j==n+1) maze[i][j]=-1;
else scanf("%d",&maze[i][j]);
SHORTPATH(maze); }
printf("\n"); }
int SHORTPATH(int maze[m2][n2])
//找迷宫 maze 的最短路径
{].x=1; sq[1].y=1; sq[1].pre=0;
front=1; rear=1;
maze[1][1]=-1;
//(i,j)为可到达点,将其入队
{
rear++;
sq[rear].x=i; sq[rear].y=j;
sq[rear].pre=front;
maze[i][j]=-1;
//标记(i,j)已到达过的点
}
if((i==m)&&(j==n))
//到达出口
{
PRINTPATH(sq,rear);
//打印路径
//标记入口点已经到达
while(front<=rear)
//队列非空
{
x=sq[front].x; y=sq[front].y; //(x,y)为出发点
for(v=0;v<8;v++)
//搜索(x,y)的 8 个相邻点(i,j)是否可到达
{
i=x+move[v].x;
j=y+move[v].y;
if(maze[i][j]==0)
/* date: 2011-03-16 direction:<球迷宫的最短路径> 规定:数字为 0 时可以通过,为 1 时不能通过,可以斜着走。 测试数据:
input: 6 8 01110111 10101010 01001111 01110011 10011000 01100110 output: (6,8) (5,7) (4,6) (4,5) (3,4) (3,3) (2,2) (1,1) */ #include<stdio.h> #define r 64 #define m2 10 #define n2 10 int m,n; typedef struct {
合集下载

c语言~走迷宫

c语言~走迷宫

本程序代码为C语言解决数据结构(严蔚敏)中关于迷宫的问题。

程序不仅实现迷宫路径查找,还实现文字描述路径功能可以直接粘贴到vc6.0中运行【代码如下】# include <stdio.h> # include <malloc.h> # define null 0typedef struct{int (*base)[2];int (*top)[2];int listlen;}sqlist;int topelem[2]; //栈顶元素void creatstack(sqlist *mazepath); //创建一个存储路径的栈void creatmap(int (*mazemap)[10]); //创建迷宫图纸void printmap(int (*mazemap)[10]);void footprint(int x,int y,int k,int (*mazemap)[10]);int position(int x,int y); //判断是否到终点int passroad(int x,int y,int (*mazemap)[10]);void findpath(int (*mazemap)[10],sqlist *mazepath); //在mazemap当中寻找mazepahtvoid printpath(sqlist *mazepath);void roadinwords(sqlist *mazepath); //文字叙述如何走迷宫void push(int x,int y,sqlist *mazepath); //栈操作void pop(sqlist *mazepath);void gettop(sqlist *mazepath);void main(){sqlist mazepath;creatstack(&mazepath); //创建一个存储路径的栈int mazemap[10][10]={1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1};// creatmap(mazemap); //创建迷宫图纸printf("迷宫原图为:\n");printmap(mazemap);findpath(mazemap,&mazepath); //在mazemap当中寻找mazepaht printf("走出迷宫图纸为:\n");printmap(mazemap);printf("走出迷宫文字叙述为:\n");roadinwords(&mazepath);// printpath(&mazepath);}void findpath(int (*mazemap)[10],sqlist *mazepath){int x,y,flag=0,k=0,next; //位置是否可通,flag=0通,1墙,2通但不可走x=1;y=1; //获取初始位置push(x,y,mazepath); //起点位置进栈footprint(x,y,6,mazemap);while(flag==0 && k!=162) //flag==1到达终点,0未到达终点{if(passroad(x,y+1,mazemap)==0)push(x,y+1,mazepath),y=y+1,footprint(x,y,6,mazemap);else if(passroad(x+1,y,mazemap)==0)push(x+1,y,mazepath),x=x+1,footprint(x,y,6,mazemap);else if(passroad(x,y-1,mazemap)==0)push(x,y-1,mazepath),y=y-1,footprint(x,y,6,mazemap);else if(passroad(x-1,y,mazemap)==0)push(x-1,y,mazepath),x=x-1,footprint(x,y,6,mazemap);elsefootprint(x,y,2,mazemap),pop(mazepath),gettop(mazepath),x=topelem[0],y= topelem[1];// printmap(mazemap);k++;flag=position(x,y); //判断是否到达终点// printf("flag==%d\n",flag);}}void creatstack(sqlist *mazepath){mazepath->base=(int (*)[2])malloc(120*sizeof(int (*)[2]));mazepath->top=mazepath->base;mazepath->listlen=120;}void push(int x,int y,sqlist *mazepath){**(mazepath->top)=x;*(*(mazepath->top)+1)=y;mazepath->top++;}void pop(sqlist *mazepath){if(mazepath->top!=mazepath->base)mazepath->top--;}void printmap(int (*mazemap)[10]){int (*p)[10];p=mazemap;int i,j;printf(" \n\n\n");for(i=0;i<10;i++){for(j=0;j<10;j++){if(j==0)printf(" ");if(*(*(p+i)+j)==0)printf("▇");else if(*(*(p+i)+j)==1)printf("□");else if(*(*(p+i)+j)==6)printf("★");elseprintf("▇");if(j==9)printf("\n");}}printf("\n\n");}void printpath(sqlist *mazepath){int (*p)[2];p=mazepath->base;while(p!=mazepath->top){printf("x=%d,y=%d\n",**p,*(*p+1));p++;}}void gettop(sqlist *mazepath){int (*p)[2];int (*q)[2];p=mazepath->base;while(p!=mazepath->top){q=p;p++;}topelem[0]=**q;topelem[1]=*(*q+1);}void footprint(int x,int y,int k,int (*mazemap)[10]){if(x<10 && y<10)*(*(mazemap+x)+y)=k;}int position(int x,int y){int flag;if(x==8 && y==8)flag=1;elseflag=0;return(flag);}int passroad(int x,int y,int (*mazemap)[10]) {int num=1;if(x<10 && y<10)num=*(*(mazemap+x)+y);return(num);}void roadinwords(sqlist *mazepath){int x=1,y=1,i=0;int (*p)[2];p=mazepath->base;p++;while(p!=mazepath->top){if(x==**p && y+1==*(*p+1))printf("向右走→→"),x=**p,y=*(*p+1);else if(x+1==**p && y==*(*p+1))printf("向下走→→"),x=**p,y=*(*p+1);else if(x==**p && y-1==*(*p+1))printf("向左走→→"),x=**p,y=*(*p+1);else if(x-1==**p && y==*(*p+1))printf("向上走→→"),x=**p,y=*(*p+1);i++;if(i%3==0)printf("\n");p++;}printf("\n");}。

C语言实验:迷宫问题(搜索,C语言实现栈、队列)

C语言实验:迷宫问题(搜索,C语言实现栈、队列)

C语⾔实验:迷宫问题(搜索,C语⾔实现栈、队列)Description给定迷宫起点和终点,寻找⼀条从起点到终点的路径。

(0,1)(2,0)起点(1,1)(1,2)(1,3)(1,4)(2,0)(2,1)(2,4)(3,0)(3,1)(3,2)终点(3,4)(4,1)上图中黄⾊代表墙,⽩⾊代表通路,起点为(1,1),终点为(3,4)。

要求搜寻策略是从起点开始按照“上、下、左、右”四个⽅向寻找终点,到下⼀个点继续按照“上、下、左、右”四个⽅⾯寻找,当该结点四个⽅向都搜寻完,但还没到终点时,退回到上⼀个点,直到找到终点或者没有路径。

⽐如上图从(1,1)开始,向上(0,1)不通,向下到(2,1);到了(2,1)后继续按“上、下、左、右”四个⽅⾯寻找,上已经⾛过,向下到(3,1);到(3,1)后上已经⾛过,下和左不通,向右到(3,2);到(3,2)四个⽅⾯都不通,回到(3,1)四个⽅向都不通,再回到(2,1),(1,1);到达(1,1)后下已经⾛过,左不通,继续向右⾛,重复这个过程最后到达(3,4)。

Input第⼀⾏两个数m和n表⽰迷宫的⾏数和列数。

迷宫⼤⼩不超过100×100第⼆⾏四个数x1,y1,x2,y2分别表⽰起点和终点的坐标。

接下来是m⾏n列的数,⽤来表⽰迷宫,1表⽰墙,0表⽰通路。

Output从起点到终点所经过的路径的坐标。

如果不存在这样的路径则输出“No Path!”。

Sample Input5 61 1 3 41 1 1 1 1 11 0 0 0 0 11 0 1 1 0 11 0 0 1 0 11 1 1 1 1 1Sample Output(1 1)(1 2)(1 3)(1 4)(2 4)(3 4)1.思路:(1)若当前点是终点,dfs函数返回1;(2)若不是终点,将此点标记为1,对该点4个⽅向进⾏搜索,实现⽅式为定义int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; 通过⼀个⼩循环: for(int i = 0; i < 4; i++) {  position nextp; nextp.x = dir[i][0] + now.x;nextp.y = dir[i][1] + now.y;...... } 进⾏搜索;若该点的下⼀个点nextp不是墙,未⾛,并且没有超界则将nextp压⼊栈中,递归调⽤dfs,若此过程经过(1)判断返回了1,说明最终找到了通往终点的路,便可以返回1,结束函数,此时栈中已储存了通往终点的路径,若没有通路,则弹出栈顶元素,根据递归原理该路径上的所有点都会弹出并标记未⾛,回溯到之前的点,继续向其他⽅向搜索,直到找到终点或遍历完整个图。

迷宫的最短路径(c++)

迷宫的最短路径(c++)

迷宫的最短路径(c++)实验题⽬(共10题, 第9题)标题:迷宫的最短路径时限:1000 ms内存限制:10000 K总时限:3000 ms描述:设计⼀个算法找⼀条从迷宫⼊⼝到出⼝的最短路径。

输⼊:迷宫的⾏和列m n 迷宫的布局输出:最短路径输⼊样例:请输⼊迷宫的⾏和列:6 8请输⼊迷宫的布局:0 1 1 1 0 1 1 11 0 1 0 1 0 1 00 1 0 0 1 1 1 10 1 1 1 0 0 1 11 0 0 1 1 0 0 00 1 1 0 0 1 1 0输出样例:最短路径为:(6,8)(5,7)(4,6)(4,5)(3,4)(3,3)(2,2)(1,1)提⽰:来源:View Code1 #include <stdio.h>2 #include <stdlib.h>3#define QUEUE_INIT_SIZE 1004#define QUEUEINCREMENT 105 typedef struct Point6 {7int x;8int y;9 } Point;10 typedef struct QElemType11 {12int pre;13 Point pos;14 } QElemType;15struct SqQueue16 {17 QElemType *base;18int front;19int rear;20int size;21 };2223void InitQueue(SqQueue&lq)24 {25 lq.base=(QElemType*)malloc(QUEUE_INIT_SIZE*sizeof(QElemType));26 lq.front=lq.rear=0;27 lq.size=QUEUE_INIT_SIZE;2829 }30void EnQueue(SqQueue&lq,QElemType e)31 {32if(lq.rear>=lq.size)33 {34 lq.base=(QElemType*)realloc(lq.base,(lq.size+QUEUEINCREMENT)*sizeof(QElemType));35 lq.size+=QUEUEINCREMENT;36 }37 *(lq.base+lq.rear)=e;38 lq.rear++;39 }40int QueueEmpty(SqQueue lq)41 {42if(lq.front==lq.rear)43 {44return1;45 }46else return0;47 }48void DeQueue(SqQueue&lq,QElemType&e)49 {50 e=*(lq.base+lq.front);51 lq.front++;5253 }54 Point NextPos( int**a,Point prePos,int i)55 {56switch(i)57 {58case1:59 prePos.y++;60break;61case2:62 prePos.x++;63 prePos.y++;64break;65case3:66 prePos.x++;67break;68case4:69 prePos.x++;70 prePos.y--;71break;72case5:73 prePos.y--;74break;75case6:76 prePos.y--;77 prePos.x--;78break;79case7:80 prePos.x--;81break;82case8:83 prePos.x--;84 prePos.y++;85break;86 }87return prePos;8889 }90int ShortestPath(int**a,SqQueue&lq,Point StartPos,Point end,int m,int n)91 {92 QElemType e;93int idx,i;94 Point prePos,curPos;95 InitQueue(lq);96 curPos = StartPos;97 e.pos = curPos;98 e.pre = -1;99 EnQueue(lq,e);100 a[curPos.x][curPos.y]=4;101while (!QueueEmpty(lq))102 {103 idx = lq.front;104 DeQueue(lq,e);105 prePos = e.pos;106for (i=1; i<=8; i++)107 {108 curPos = NextPos(a,prePos,i);109if (0<=curPos.x&&curPos.x<m&&curPos.y>=0&&curPos.y<n&&a[curPos.x][curPos.y]==0) 110 {111 e.pos = curPos;112 e.pre = idx;113 EnQueue(lq, e);114 a[curPos.x][curPos.y]=4;115 }116if (curPos.x == end.x && curPos.y == end.y) return1;117 }118 }119return0;120 }121void PrintPath( SqQueue&lq)122 {123int i;124 QElemType e;125 i=lq.rear-1;126do127 {128 e=*(lq.base+i);129 printf("(%d,%d)\n",e.pos.x+1,e.pos.y+1); 130131 i = e.pre;132133 }134while(i!=-1);135 }136137int main()138 {139int m,n,**a,i,j;140 SqQueue lq;141 Point StartPos,end;142 scanf("%d%d",&m,&n);143 StartPos.x=0;144 StartPos.y=0;145 end.x=m-1;146 end.y=n-1;147 a=(int**)malloc(m*sizeof(int*));148for(i=0; i<m; i++)149 {150 a[i]=(int*)malloc(n*sizeof(int));151 }152for(i=0; i<m; i++)153 {154for(j=0; j<n; j++)155 {156 scanf("%d",&a[i][j]);157 }158 }159 ShortestPath(a,lq,StartPos,end,m,n);160 PrintPath(lq);161162163return0;164 }。

用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语言实现深度 优先搜索算法
深度优先搜索算法的基本原理

c语言走迷宫代码

c语言走迷宫代码

c语言走迷宫代码以下是一个简单的 C 语言走迷宫代码示例,使用了递归算法: ```c#include <stdio.h>#include <stdlib.h>int main() {int size, row, col, choice, i, j;maze[0][0] = "*";maze[1][0] = "O";maze[0][1] = "O";maze[1][1] = "*";size = 2;row = 2;col = 2;while (1) {printf("Enter row: ");scanf("%d", &row);printf("Enter col: ");scanf("%d", &col);if (row < 0 || row > size || col < 0 || col > size) { printf("Invalid row or col. Try again.");}if (maze[row][col] != "*") {printf("Current cell is free. Try again. ");continue;}maze[row][col] = "X";printf("Enter a choice (1-6): ");scanf("%d", &choice);switch (choice) {case 1:row++;col = 0;break;case 2:row--;col = 0;break;case 3:col++;break;col--;break;case 5:row--;col = 1;break;case 6:row++;col = 1;break;default:printf("Invalid choice. Try again. ");continue;}}printf(" maze: ");for (i = 0; i < size * size; i++) { for (j = 0; j < size; j++) {if (maze[i][j] == "*")printf("*");elseprintf("%c", maze[i][j]);}printf("");}return 0;}```该程序首先初始化了一个 2x2 的迷宫,其中 `maze[0][0]` 和`maze[1][0]` 分别标记为 `"O"` 和 `"*"`,其他地方都为空。

c++迷宫问题最短路径

c++迷宫问题最短路径

c++迷宫问题最短路径// newcoder_xiaohongshu_1.cpp : 此⽂件包含 "main" 函数。

程序执⾏将在此处开始并结束。

//#include "pch.h"#include <iostream>#include <queue>#include <map>using namespace std;/*pair<int, int > p = make_pair(1, 2);pair<int, int> p(1, 2);p= new pair<int,int>(1,2)*/int dx[4] = {0,1,0,-1};int dy[4]= {1,0,-1,0};//迷宫地图,1代表墙壁,0代表通路int N = 10;int mat[10][10] = { {1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,0,1},{1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},{1,0,1,0,0,0,1,0,0,1},{1,0,1,1,1,0,1,1,0,1},{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}};class Dot {public:int x;int y;Dot(int x,int y):x(x),y(y){}};class WideBlock:public Dot{public:WideBlock *parent;WideBlock(int x,int y,WideBlock* p):Dot(x,y),parent(p){}};void print(WideBlock *p)//递归顺序输出{if (!p->parent){cout << "\n(" << p->x << "," << p->y << ")" << ";";}else{print(p->parent);cout << "(" << p->x << "," << p->y << ")" << ";";}}int main(){WideBlock *s=new WideBlock(1, 1, NULL), *end=new WideBlock(8, 8, NULL); queue<WideBlock*> q;mat[1][1] = 1;q.push(s);while (!q.empty()){WideBlock* cur = q.front();q.pop();int x = cur->x;int y = cur->y;if (x == end->x && y == end->y){end = cur;break;}if (y + dy[0] < N && mat[x][y + dy[0]] == 0){q.push(new WideBlock(x, y + dy[0],cur));mat[x][y + dy[0]] = 1;}if (x + dx[1] < N && mat[x+dx[1]][y] == 0){q.push(new WideBlock(x+dx[1], y,cur));mat[x+dx[1]][y] = 1;}if (y + dy[2] > -1 && mat[x][y + dy[2]] == 0){q.push(new WideBlock(x, y + dy[2],cur));mat[x][y + dy[2]] = 1;}if (x + dx[3] >-1 && mat[x+dx[3]][y] == 0){q.push(new WideBlock(x+dx[3], y,cur));mat[x+dx[3]][y] = 1;}}WideBlock *tmp = end;while (tmp){cout << "(" << tmp->x << "," << tmp->y << ")" << ";";tmp = tmp->parent;}tmp = end;print(tmp);std::cout << "Hello World!\n";return 0;}// 运⾏程序: Ctrl + F5 或调试 >“开始执⾏(不调试)”菜单// 调试程序: F5 或调试 >“开始调试”菜单// ⼊门提⽰:// 1. 使⽤解决⽅案资源管理器窗⼝添加/管理⽂件// 2. 使⽤团队资源管理器窗⼝连接到源代码管理// 3. 使⽤输出窗⼝查看⽣成输出和其他消息// 4. 使⽤错误列表窗⼝查看错误// 5. 转到“项⽬”>“添加新项”以创建新的代码⽂件,或转到“项⽬”>“添加现有项”以将现有代码⽂件添加到项⽬// 6. 将来,若要再次打开此项⽬,请转到“⽂件”>“打开”>“项⽬”并选择 .sln ⽂件。

数据结构迷宫最短路径实验报告

实验报告课程名:数据结构(C语言版)实验名:迷宫问题II姓名:班级:学号:撰写时间:2014/10/10一实验目的与要求1. 了解栈的应用2. 利用栈在迷宫中找到一条路二实验内容•一个迷宫如图1所示, 是由若干个方格构成的一个矩形, 其中有唯一的一个入口(用⃝标示), 有唯一的一个出口(用△标示). 图中深色的方格无法到达, 浅色的方格都是可以到达的. 每一次只能从当前方格前进到与当前方格有公共边的方格中(因此前进方向最多有四个).•本次实验的迷宫问题要求找到从入口到出口的最短的路.图1:迷宫三实验结果与分析程序:#include <stdio.h>#include <stdlib.h>int Maze(int ox,int oy,int ex,int ey,int rnum,int cnum,int a[rnum][cnum]){int b[rnum][cnum];int i,j,Znum=0;for(i=0;i<rnum;++i){for(j=0;j<cnum;++j){b[i][j]=a[i][j];if(a[i][j]==0){Znum=Znum+1;}}}int Qx[Znum+1], Qy[Znum+1], P[Znum+1], head=0, tail=0; for(i=0;i<Znum+1;++i){Qx[i]=-10;Qy[i]=-10;P[i]=-10;}/*int dx[4] = {0,1,0,-1};int dy[4] = {-1,0,1,0};int neighbor_num = 4;*/int dx[8] = {-1, 0, 1,1,1,0,-1,-1};int dy[8] = {-1,-1,-1,0,1,1, 1, 0};int neighbor_num = 8;if(ox==ex && oy==ey){printf("(%d,%d)",ox,oy);}else{Qx[tail]=ox;Qy[tail]=oy;P[tail]=-1;++tail;b[ox][oy]=2;}int brand = -1;while(tail>head){for(i=0;i<neighbor_num;i++){int tx = Qx[head]+dx[i];int ty = Qy[head]+dy[i];if(b[tx][ty]==0){if(tx==ex && ty==ey){printf("(%d,%d), ",tx,ty);int t = head;while(t>=0){printf("(%d,%d), ",Qx[t],Qy[t]);t=P[t];}head=tail;brand=1;break;}else{Qx[tail]=tx;Qy[tail]=ty;P[tail]=head;++tail;b[tx][ty]=2;}}}++head;}return(brand);}int main(int argc, char *argv[]) {int rnum = 10;int cnum = 10;int a[10][10]={{1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,0,1},{1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},{1,0,1,0,0,0,1,0,0,1},{1,0,1,1,1,0,1,1,0,1},{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}};//假设外面有一层不可到达的方块,故迷宫成了10乘10型int ox=1,oy=1,ex=rnum-2,ey=cnum-2;int brand = Maze(ox,oy,ex,ey,rnum,cnum,a);if(brand<0){printf("There is no way\n");}return 0;}图1:实验结果截图。

迷宫最短路径的C++实现(队列:广度优先)

迷宫最短路径的C++实现(队列:广度优先)[cpp]view plainc opy1.#include<iostream>2.#include<queue>3.#include<string>ing namespace std;5.struct point{6.int x;7.int y;8. point *last;//上一步的坐标9.};10.int main(){11.while(1){12.int row, col, i, j;13. cout<<"请输入迷宫图的行数和列数:";14. cin>>row>>col;15.int **a = new int* [row+2];16.for(i = 0; i < row+2; ++i){17. a[i] = new int[col+2];18. }19. cout<<"请输入迷宫图(1代表墙壁,0代表通路):"<<endl;20.for(i = 1; i < row+1; ++i){21.for(j = 1; j < col+1; ++j){22. cin>>a[i][j];23. }24. }25.for(i = 0; i < col+2; ++i){//加墙26. a[0][i] = 1;27. a[row+1][i] = 1;28. }29.for(i = 1; i < row+1; ++i){//加墙30. a[i][0] = 1;31. a[i][col+1] = 1;32. }33. queue<point*> q;34. point *start = (point*)malloc(sizeof(point));//起点35. cout<<"请输入起点坐标(范围1,1到"<<row<<","<<col<<"):";36. cin>>start->x>>start->y;37. start->last = start;38. q.push(start);39.40. a[start->x][start->y] = 2;41.42. point end;//终点43. cout<<"请输入终点坐标(范围1,1到"<<row<<","<<col<<"):";44. cin>>end.x>>end.y;45.int aspect[4][2] = {{0, -1},{0, 1},{-1, 0},{1, 0}};//转向:上下左右46.int flag = 0;//是否有路可走的标志47.while(!q.empty()){48. point *front = q.front();49. q.pop();//弹出队头50.if(front->x == end.x && front->y == end.y){51. flag = 1;52. cout<<"成功找到出路."<<"最少需要"<<a[front->x][front->y]-2<<"步。

c语言迷宫代码

c语言迷宫代码C语言迷宫代码是指用C语言编写的程序,用于生成和解决迷宫问题的算法。

迷宫通常由一个矩形网格组成,其中包含墙壁和通道。

目标是找到从迷宫的起点到终点的路径,同时避开墙壁。

下面是一个简单的示例代码,用于生成迷宫:```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define ROWS 10#define COLS 10typedef struct {int x;int y;} Point;void generateMaze(int maze[ROWS][COLS]) {for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {if (i % 2 == 0 || j % 2 == 0) { maze[i][j] = 1; // 墙壁} else {maze[i][j] = 0; // 通道}}}}void printMaze(int maze[ROWS][COLS]) {for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {printf('%d ', maze[i][j]);}printf('');}}int main() {int maze[ROWS][COLS];generateMaze(maze);printMaze(maze);return 0;}```在上面的代码中,我们使用一个二维数组来表示迷宫。

数组中的值为1表示墙壁,值为0表示通道。

使用generateMaze函数,我们将迷宫的墙壁和通道初始化为适当的值。

然后使用printMaze函数打印迷宫。

通过运行上面的代码,我们可以得到一个简单的迷宫的表示:```1 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 1```当然,上述代码只是生成了一个简单的迷宫,还没有解决迷宫问题。

C语言自动生成查找迷宫最短路径的代码

C语言自动生成查找迷宫最短路径的代码#include#include#include#include#includeusing namespace std;#define OVERFLOW 0#define OK 1#define ERROE 0#define TRUE 1#define FALSE 0#define SIZE 102//迷宫的最大范围typedef int Status;typedef struct{int x;int y;}PosType;//坐标位置typedef struct {PosType seat; //通道块在迷宫中的"坐标位置"int di; //从上一通道块走向此通道块的"方向"}SElemType;void Random(int (*mg)[SIZE],int size,PosType start,PosType end);/*随机生成迷宫的函数/*为了能够让尽量能通过,将能通过的块和不能通过的块数量比大致为3:1*/Status Pass(PosType e,int (*mg)[SIZE]);//当前块可否通过Status FootPrint(PosType e,int (*mg)[SIZE]);//留下通过的足迹PosType NextPos(PosType e,int dir);//下一步Status Equal(PosType e1,PosType e2);//e1与e2的位置坐标是否相同Status MarkPath(PosType e,int (*mg)[SIZE],int di);//对最短可行路径上的“通道块”进行标记PosType FrontPos(PosType e,int dir);//寻找当前通道块的上一步的位置Status PathPrint(stack s,int (*mg)[SIZE]);//迷宫最短路径的标记Status PathClean(int (*mg)[SIZE],stack s);//路径清除Status MazePath(PosType start,PosType end,int (*mg)[SIZE],stack &s);/*迷宫函数/* 若迷宫maze中从入口start到出口end的通道,则求得一条存放在栈中/* 并返回TRUE;否则返回FALSE*/void PrintMaze(int (*mg)[SIZE],int size);//打印迷宫Status Check(char &choice);//确认输入正确int main(){stack s;int mg[SIZE][SIZE]={1},size;PosType start,end;char choice;system("mode con cols=220 lines=220");printf("\n==================迷宫最短路径游戏==================");printf("\n说明:■不能走的区域");printf("\n '空格'代表可通过的区域");printf("\n默认起点为左上角位置,默认终点为右下角位置\n");printf("\n================================ ============\n");printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);while((size>SIZE-2)||(size<1)){printf("输入有误!\n");printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);}size+=2;//补上外围getchar();//跳过'\n'start.x=1;start.y=1; //起点坐标end.x=size-2;end.y=size-2; //终点坐标Random(mg,size,start,end);PrintMaze(mg,size);while(!((choice=='Q')||(choice=='q'))){printf("是否使用该迷宫?(y/n)\n");Check(choice);if((choice=='Y')||(choice=='y')){PathClean(mg,s);}while((choice=='n')||(choice=='N')){while(!s.empty())s.pop();choice=' ';printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);while((size>SIZE-2)||(size<1)){printf("输入有误!\n");printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);}size+=2;//补上外围start.x=1;start.y=1;//起点坐标end.x=size-2;end.y=size-2; //终点坐标getchar();//跳过'\n'Random(mg,size,start,end);PrintMaze(mg,size);printf("是否使用该迷宫?(y/n)\n");Check(choice);}printf("是否人工选择起点和终点(y/n)?【默认:起点(1,1),终点(%d,%d)】\n",size-2,size-2);Check(choice);if((choice=='y')||(choice=='Y')){printf("请输入“起点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&start.x,&start.y);while(((start.x>size-2)||start.x<1)||((start.y>size-2)||(start.y<1))||!Pass(start,mg)){if(!Pass(start,mg)) printf("些位置不能为“起点”!\n");else printf("输入有误!\n");printf("请输入“起点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&start.x,&start.y);}printf("请输入“终点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&end.x,&end.y);while(((end.x>size-2)||end.x<1)||((end.y>size-2)||(end.y<1))||!Pass(end,mg)||Equal(start,end)){if(!Pass(end,mg)) printf("些位置不能为“终点”!\n");else if(Equal(start,end)) printf("该位置已为起点!\n");else printf("输入有误!\n");printf("请输入“终点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&end.x,&end.y);}getchar();//跳过'\n'}MazePath(start,end,mg,s);PrintMaze(mg,size);printf("退出游戏请输入\"Q\"否则继续游戏!\n");choice=getchar();getchar();//跳过'\n'}printf("\n==========程序退出,感谢使用!==========\n");return 0;}void Random(int (*mg)[SIZE],int size,PosType start,PosType end){int i,j,k;srand(time(NULL));for(j=0;j<size;j++)mg[0][j]=mg[size-1][j]=1; /*设置迷宫外围"不可走",保证只有一个出口和入口*/for(i=1;i<size-1;i++)mg[i][0]=mg[i][size-1]=1; /*设置迷宫外围"不可走",保证只有一个出口和入口*/for(i=1;i<size-1;i++)for(j=1;j<size-1;j++){k=rand()%4; //随机生成0、1、2、4三个数if(k)mg[i][j]=0;else{mg[i][j]=1;}//else}mg[start.y][start.x]=0;mg[end.y][end.x]=0; //将入口、出口设置为"0"即可通过}Status Pass(PosType e,int (*mg)[SIZE]){if (mg[e.y][e.x]==0) //0时可以通过return OK; // 如果当前位置是可以通过,返回1 return OVERFLOW; // 其它情况返回0}Status FootPrint(PosType e,int (*mg)[SIZE]){mg[e.y][e.x]=7;return OK;}PosType NextPos(PosType e,int dir){PosType E;switch(dir){case 1:E.x=e.x+1; //向右E.y=e.y;break;case 2:E.x=e.x; //向下E.y=e.y+1;break;case 3:E.x=e.x-1; //向左E.y=e.y;break;case 4:E.x=e.x; //向上E.y=</size-1;j++){</size-1;i++)</size-1;i++)</size;j++)e.y-1;break;}return E;}Status Equal(PosType e1,PosType e2){if((e1.x==e2.x)&&(e1.y==e2.y))return TRUE;return FALSE;}Status MarkPath(PosType e,int (*mg)[SIZE],int di) {switch(di){case 1://向右mg[e.y][e.x]=11;break;case 2://向下mg[e.y][e.x]=12;break;case 3://向左mg[e.y][e.x]=13;break;case 4://向上mg[e.y][e.x]=14;break;}return OK;}PosType FrontPos(PosType e,int dir) {PosType E;switch(dir){case 1:E.x=e.x-1; //向左E.y=e.y;break;case 2:E.x=e.x; //向上E.y=e.y-1;break;case 3:E.x=e.x+1; //向右E.y=e.y;break;case 4:E.x=e.x; //向下E.y=e.y+1;break;}return E;}Status PathPrint(stack s,int (*mg)[SIZE]) {SElemType e,front,tail;int di;e=s.top();tail=e;s.pop();MarkPath(e.seat,mg,1);while(!s.empty()){front=s.top();s.pop();if(Equal(front.seat,FrontPos(e.seat,e.di))) {di=e.di;e=front;MarkPath(e.seat,mg,di);}}mg[tail.seat.y][tail.seat.x]=20;mg[e.seat.y][e.seat.x]=10;return OK;Status PathClean(int (*mg)[SIZE],stack s){SElemType e;while(!s.empty()){e=s.top();s.pop();mg[e.seat.y][e.seat.x]=0;}return OK;}Status MazePath(PosType start,PosType end,int (*mg)[SIZE],stack &s){queue q;SElemType e;int di=0;e.di=di;e.seat=start;// 设定"当前位置"为"入口位置"q.push(e);s.push(e);do{e=q.front();q.pop();for(di=1;di<=4;di++)e.seat=NextPos(e.seat,di);e.di=di;if(Pass(e.seat,mg)){q.push(e);s.push(e);FootPrint(e.seat,mg);if(Equal(e.seat,end)){PathPrint(s,mg);return TRUE;}}e.seat=FrontPos(e.seat,di);}}while(!q.empty());printf("\n\n囧 ! 不能到达终点!"); return FALSE;}void PrintMaze(int (*mg)[SIZE],int size) {int i,j;printf("\n");for(i=0;i<size;i++){for(j=0;j<size;j++){switch(mg[i][j]){case 0: case 7: printf(" "); break; case 1: printf("■"); break; case 10: printf("起"); break; case 20: printf("终"); break; case 11: printf("→"); break; case 12: printf("↓"); break; case 13: printf("←"); break; case 14: printf("↑"); break;}}printf("\n"); }printf("\n");}Status Check(char &choice){while(!(((choice=getchar())=='y')||(choice=='n')||(choice=='Y ')||(choice=='N')))//非正确输入{if(choice!='\n'){printf("请输入确定选择(y/n)\n");getchar();}}getchar();//跳过'\n'return OK;}</size;j++){</size;i++){。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档