算法3-3:迷宫

有一个 10 x 10 的迷宫,起点是‘S’,终点是‘E’,墙是‘#’,道路是空格。一个机器人从起点走到终点。当机器人走到一个通道块,前面已经没有路可走时,它会转向到当前面向的右手方向继续走。如果机器人能够过,则留下足迹‘*’,如果走不通,则留下标记‘!’。下面给出书中的算法,请你模拟机器人的走法输出最终的状态。

Input

一个 10 x 10 的二维字符数组。

Output

机器人走过的路径状态。

Sample Input
##########
#S #   # #
#  #   # #
#    ##  #
# ###    #
#   #    #
# #   #  #
# ### ## #
##      E#
##########

Sample Output
##########
#**#!!!# #
# *#!!!# #
#**!!##  #
#*###    #
#***#    #
# #***#  #
# ###*## #
##   ****#
##########
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define size_maze  400
typedef struct PosType_1{
	int x,y,fangxiang;
}PosType_1;
typedef struct node{
	PosType_1 *base,*top;
}MazeType;
void init_MazeType(MazeType *s)
{
	s->base = (PosType_1 *)malloc(sizeof(PosType_1) * size_maze);
	s->top = s->base;
}
void push(MazeType *s,PosType_1 n)
{
	*(s->top) = n;
	s->top++;
}
void shuru(char a[15][15],PosType_1 *zhongdian,PosType_1 *qidian)
{
	char b[15];
	for(int i = 0;i < 10;i++)
	{
		gets(b);
		for(int j = 0;j < 10;j++)
		{
			a[i][j] = b[j];
			if(a[i][j] == 'S')
			{
				qidian->x = i;
				qidian->y = j;
			}
			if(a[i][j] == 'E')
			{
				zhongdian->x = i;
				zhongdian->y = j;
			}
		}
	}
}
void pop(MazeType *s,PosType_1 *old)
{
	s->top -= 1;
	*old = *(s->top);
}
int main(void)
{
	char a[15][15];
	MazeType s;
	init_MazeType(&s);
	PosType_1 now,old,zhongdian,qidian;
	now.fangxiang = 1;
	shuru(a,&zhongdian,&qidian);
	a[qidian.x][qidian.y] = '*';
	now.x = qidian.x;
	now.y = qidian.y;
	a[zhongdian.x][zhongdian.y] = ' ';
	push(&s,now);
	while(now.x != zhongdian.x||now.y != zhongdian.y)
	{
		if(now.fangxiang == 1)
		{
			if(a[now.x][now.y + 1] == ' ')
			{
				a[now.x][now.y + 1] = '*';
				now.y += 1;
				push(&s,now);
			}
			else
			{
				now.fangxiang += 1;
			}
		}
		if(now.fangxiang == 2)
		{
			if(a[now.x + 1][now.y] == ' ')
			{
				a[now.x + 1][now.y] = '*';
				now.x += 1;
				now.fangxiang = 1;
				push(&s,now);
				//
			}
			else
			{
				now.fangxiang += 1;
			}
		}
		if(now.fangxiang == 3)
		{
			if(a[now.x][now.y - 1] == ' ')
			{
				a[now.x][now.y - 1] = '*';
				now.y -= 1;
				now.fangxiang = 1;
				push(&s,now);
			}
			else
			{
				now.fangxiang += 1;
			}
		}
		if(now.fangxiang == 4)
		{
			if(a[now.x - 1][now.y] == ' ')
			{
				a[now.x - 1][now.y] = '*';
				now.x -= 1;
				now.fangxiang = 1;
				push(&s,now);
			}
			else
			{
				pop(&s,&old);
				a[old.x][old.y] = '!';
				now.x = ( (s.top)-1)->x;
				now.y = ( (s.top)-1)->y;
				now.fangxiang = 1;
			}
		}
	}
	for(int i_2 = 0;i_2 < 10;i_2++)
	{
		for(int j_1 = 0;j_1 < 10;j_1++)
		{
			printf("%c",a[i_2][j_1]);
		}
		printf("\n");
	}
	return 0;
}
原创文章 382 获赞 114 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45949073/article/details/105709687
3-3