maze.c

来自「《数据结构-使用C语言》第三版」· C语言 代码 · 共 87 行

C
87
字号
//迷宫
#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("file open error!");
		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);
	
	close(fp);
}

int main()
{
	Maze m;
	int start;
	while(scanf("%d",&start)!=EOF)
	{
		
		CreatMaze("Maze1.dat",&m);
		if(TravMaze(&m,start))
		printf("YES\n");
		else 
		printf("NO\n");
	}
	return 0;
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?