poj最短生成路3984

定义一个二维数组: 

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)
#include<algorithm>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<queue> 
#include<stdio.h>
int dist[10][10];
int visit[10][10];
int gra[10][10];
const int dx[4] = {-1,1,0,0};
const int dy[4] = {0,0,-1,1};
using namespace std;
struct node
{
	int x,y;
};
void bfs(int x,int y)
{
	int i;
	queue<node>que;
	memset(visit,0,sizeof(visit));
	memset(dist,0,sizeof(dist));
	node head,next;
	head.x = x;
	head.y = y;
	dist[x][y] = 0;
	que.push(head);
	visit[x][y] = 1;
	while(!que.empty())
	{
	 head = que.front();
		que.pop();
		if((head.x == 5) && (head.y == 5))
		{
			return ;
		}
		for(i=0; i<4; i++)
		{
			int xx = head.x + dx[i];
			int yy = head.y + dy[i];
			if(!visit[xx][yy] && (gra[xx][yy] == 0) && (xx >= 1) && (xx <= 5) &&(yy >= 1) && (yy <= 5))
			{
				visit[xx][yy] = 1;
				dist[xx][yy] = dist[head.x][head.y] + 1;
				next.x = xx,next.y = yy;
				que.push(next);
			}
		}
	}
}
void print_path(node n1,node n2)
{
	int i;
	if((n2.x == n1.x) && (n1.y == n2.y))
		return;
	for(i=0; i<4; i++)
	{
		int xx = n2.x + dx[i];
		int yy = n2.y + dy[i];
		if((dist[n2.x][n2.y] == dist[xx][yy] + 1) && visit[xx][yy])
		{
			node n3;
			n3.x =xx,n3.y =yy;
			print_path(n1,n3);
			printf("(%d, %d)\n",n3.x-1,n3.y-1);
		}
	}
	return ;
}
int main()
{
	int i,j;
	for(i=1; i<=5; i++)
		for(j=1; j<=5; j++)
			scanf("%d",&gra[i][j]);
	bfs(1,1);	
	node n1,n2;
	n1.x = 1, n1.y = 1;
	n2.x = 5, n2.y = 5;
	print_path(n1,n2);
	printf("(4, 4)");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41453511/article/details/81093996