poj 3894 迷宫问题

迷宫问题

Description

定义一个二维数组: 
int maze[5][5] = {

	0, 1, 0, 0, 0,

	0, 1, 0, 1, 0,

	0, 0, 0, 0, 0,

	0, 1, 1, 1, 0,

	0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
 
  
 
  
-----------------------------------
不多说了,BFS在迷宫问题中的简单应用
 
  
#include
#include


int map[100][100];
int visited[100][100];
int fa[100][100];
int q[10010];
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int row=5,col=5;


struct node
{
	int x,y;
}start,end;


void bfs(int x,int y)
{
	int front=0,rear=0,d,u;
	int nx,ny;
	u = x*col + y;
	visited[x][y] = 1;
	fa[x][y] = u;
	q[rear++] = u;
	while(front	{
		u = q[front++];
		x = u/col;y = u%col;
		for(d=0;d<4;d++)
		{
			nx = x+dir[d][0];
			ny = y+dir[d][1];
			if(nx>=0 && nx=0 && ny			{
				fa[nx][ny] = u;
				if(nx==end.x && ny==end.y)
					return ;
				else
				{
					visited[nx][ny] = 1;
					int v = nx*col + ny;
					q[rear++] = v;
				}
			}
		}
	}




}


void print_path()
{
	int k=0;
	int i,j,x,y;
	q[k++] = end.x*col + end.y;
	
	i = end.x;
	j = end.y;
	while(i!=start.x || j!=start.y)
	{
		x = i,y = j;
		i = fa[x][y]/col;
		j = fa[x][y]%col;
		q[k++] = i*col + j;
	}
	for(i=k-1;i>=0;i--)
	{
		printf("(%d, %d)\n",q[i]/col,q[i]%col);
	}	
}
int main()
{
	int i,j;
	int tmp;
	//scanf("%d%d",&row,&col);
	for(i=0;i	{
		for(j=0;j		{
			scanf("%d",&tmp);
			map[i][j] = !tmp;
		}
	}
	start.x = 0;start.y = 0;
	end.x = 4;end.y = 4;
	//scanf("%d%d",&start.x,&start.y);
	//scanf("%d%d",&end.x,&end.y);


	memset(q,0,sizeof(q));
	memset(visited,0,sizeof(visited));
	memset(fa,0,sizeof(fa));


	bfs(start.x,start.y);
	print_path();


	return 0;
}

你可能感兴趣的:(搜索)