您的位置:首页 > 编程语言 > C语言/C++

C语言 解决迷宫问题练习

2014-07-11 15:29 183 查看
利用C语言来解决类似迷宫的问题,下面例子分别用两种方法来解决!

[Problem]

There is a maze as shown in the diagram below. In the maze in the form of a 100*100 matrix, the white background represents the road while the yellow background represents the wall.

Assuming the upper left corner block to be (0, 0), the horizontal direction to be x direction and vertical direction to be y direction, the starting point of the maze is (1. 1) and the arriving point is (13, 13).

Create a program to determine if there is a path to reach the arriving point from the starting point.

In the following example, there is the path.

#include<stdio.h>

typedef struct node
{
int x;
int y;
}Node;

void push(Node shu[10000],Node n);
Node pop(Node shu[10000]);
int empty(Node shu[10000]);

int front=-1;
int rear=-1;

void main()
{
int L,T;
freopen("maze2_test_input.txt","r",stdin);
//freopen("test.txt","r",stdin);

for(L=0;L<10;L++)
{
int i,j;
int result=0;
front=-1;
rear=-1;
Node shu[10000];
Node n;
char maze[100][101];
scanf("%d",&T);
for(i=0;i<100;i++)
scanf("%s",maze[i]);

for(i=0;i<100;i++)
{
for(j=0;j<100;j++)
if(maze[i][j]=='2')
{
n.x=i;
n.y=j;
push(shu,n);
}
}

while(1)
{
if(!empty(shu))
{
n=pop(shu);
Node n1,n2,n3,n4;
if(maze[n.x][n.y]=='3')
{
result=1;
break;
}
maze[n.x][n.y]='1';
if(maze[n.x+1][n.y]!='1'&&maze[n.x+1][n.y]!='2')
{
n1.x=n.x+1;
n1.y=n.y;
push(shu,n1);
//printf("(%d,%d) ",n1.x,n1.y);
}
if(maze[n.x-1][n.y]!='1'&&maze[n.x-1][n.y]!='2')
{
n2.x=n.x-1;
n2.y=n.y;
push(shu,n2);
//printf("(%d,%d) ",n2.x,n2.y);
}
if(maze[n.x][n.y+1]!='1'&&maze[n.x][n.y+1]!='2')
{
n3.x=n.x;
n3.y=n.y+1;
push(shu,n3);
//printf("(%d,%d) ",n3.x,n3.y);
}
if(maze[n.x][n.y-1]!='1'&&maze[n.x][n.y-1]!='2')
{
n4.x=n.x;
n4.y=n.y-1;
push(shu,n4);
//    printf("(%d,%d) ",n4.x,n4.y);
}

}
else
{
result=0;
break;
}
}

printf("#%d %d\n",T,result);
//printf("%d,%d\n",n.x,n.y);

}
}

void push(Node shu[10000],Node n)
{
rear++;
shu[rear].x=n.x;
shu[rear].y=n.y;
}

Node pop(Node shu[10000])
{
Node n;
if(!empty(shu))
{
front++;
n.x=shu[front].x;
n.y=shu[front].y;
}
return n;
}

int empty(Node shu[10000])
{
if(front==rear)
return 1;
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: