P127-P128 例6-10 设计求解迷宫问题的算法并用实际例子测试。
迷宫问题描述:一个迷宫是一些互相连通的交叉路口的集合,给定一个迷宫路口,一个迷宫出口,当从入口到出口存在通路时,输出其中的一条通路;当从入口到出口不存在通路时,输出无通路存在。每个交叉路口,除进来的路外还有三个路口,分别是向左、向前和向右。为简化设计,假设迷宫中不存在环路。如图6-8所示是一个没有环路的迷宫示意图。
头文件:P128-P130回溯算法求解迷宫问题.h
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int left;
int forward;
int right;
}InterSection;
typedef struct
{
int mazeSize;
InterSection *intSec;
int Exit;
}Maze;
int TravMaze(Maze *m,int currSetValue)
{
if(currSetValue>0)
{
if(currSetValue==m->Exit)
{
printf("%d <==",currSetValue);
return 1;
}
else if(TravMaze(m,m->intSec[currSetValue].left)==1)
{
printf("%d <==",currSetValue);
return 1;
}
else if(TravMaze(m,m->intSec[currSetValue].forward)==1)
{
printf("%d <==",currSetValue);
return 1;
}
else if(TravMaze(m,m->intSec[currSetValue].right)==1)
{
printf("%d <==",currSetValue);
return 1;
}
}
return 0;
}
void CreatMaze(char *filename,Maze *m)
{
FILE *fp;
int i;
fp=fopen(filename,"r");
if(!fp)
{
printf("数据文件无法打开!");
return;
}
fscanf(fp,"%d",&m->mazeSize);
m->intSec=(InterSection*)malloc(sizeof(InterSection)*(m->mazeSize+1));
for(i=1;i<=m->mazeSize;i++)
fscanf(fp,"%d%d%d",&m->intSec[i].left,&m->intSec[i].forward,&m->intSec[i].right);
fscanf(fp,"%d",&m->Exit);
fclose(fp);
}
源文件:P127-P128 例6-10.c
#include<stdio.h>
#include"P128-P130回溯算法求解迷宫问题.h"
int main()
{
Maze m;
int start=1;
CreatMaze("Maze1.dat",&m);
if(TravMaze(&m,start))
printf("\n此迷宫的一条通路如上所示!");
else
printf("\n此迷宫无通路!");
return 0;
}
Maze1.dat:
6
0 2 0
3 5 6
0 0 4
0 0 0
0 0 0
7 0 0
7
在VS2019下,需将头文件fopen和fscanf做些修改,所以在VS2019下头文件P128-P130回溯算法求解迷宫问题.h为:
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int left;
int forward;
int right;
}InterSection;
typedef struct
{
int mazeSize;
InterSection* intSec;
int Exit;
}Maze;
int TravMaze(Maze* m, int currSetValue)
{
if (currSetValue > 0)
{
if (currSetValue == m->Exit)
{
printf("%d <==", currSetValue);
return 1;
}
else if (TravMaze(m, m->intSec[currSetValue].left) == 1)
{
printf("%d <==", currSetValue);
return 1;
}
else if (TravMaze(m, m->intSec[currSetValue].forward) == 1)
{
printf("%d <==", currSetValue);
return 1;
}
else if (TravMaze(m, m->intSec[currSetValue].right) == 1)
{
printf("%d <==", currSetValue);
return 1;
}
}
return 0;
}
void CreatMaze(char* filename, Maze* m)
{
FILE* fp;
int i;
fopen_s(&fp, filename, "r");
if (!fp)
{
printf("数据文件无法打开!");
return;
}
fscanf_s(fp, "%d", &m->mazeSize);
m->intSec = (InterSection*)malloc(sizeof(InterSection) * (m->mazeSize + 1));
for (i = 1; i <= m->mazeSize; i++)
fscanf_s(fp, "%d%d%d", &m->intSec[i].left, &m->intSec[i].forward, &m->intSec[i].right);
fscanf_s(fp, "%d", &m->Exit);
fclose(fp);
}