POJ 3984 迷宫问题(bfs)

题意:

定义一个二维数组它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走

要求编程序找出从左上角到右下角的最短路线

思路:

bfs基础题,在结构体内定义一个数组保存路径即可

代码如下:

#include<cstdio>  
#include<cstring>
#include<queue>
using namespace std;  

int map[10][10], vis[10][10]; 

int f[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

struct node
{
	int x, y, st;
	int rute[25][2];
};

bool check(node b)
{
	if(vis[b.x][b.y]) return 1;
	if(b.x < 0 || b.y  < 0 || b.x > 4 || b.y > 4)return 1;
	else if(map[b.x][b.y] == 1) return 1;
	return 0;
}

node bfs()
{
	memset(vis, 0, sizeof(vis));
	node s, nex;
	s.x = 0, s.y = 0, s.st = 0, s.rute[s.st][0] = s.x, s.rute[s.st][1] = s.y;
	queue<node>q;
	q.push(s);
	while(!q.empty())
	{
		node a = q.front();
		q.pop();
		if(a.x == 4 && a.y == 4)return a;
		for(int i = 0; i < 4; i++)
		{
			nex = a;
			nex.x += f[i][0];
			nex.y += f[i][1];
			if(check(nex)) continue;
			nex.st += 1;
			nex.rute[nex.st][0] = nex.x, nex.rute[nex.st][1] = nex.y;
			q.push(nex);
		}
	}
}

int main()
{
	for(int i = 0; i < 5; i++)
	{
		for(int j = 0; j < 5; j++)
		{
			scanf("%d", &map[i][j]);
		}	
	}
	node ans = bfs();
	for(int i = 0; i <= ans.st; i++)
	{
		printf("(%d, %d)\n", ans.rute[i][0], ans.rute[i][1]);
	}
	return 0;
}
    原文作者:BFS
    原文地址: https://blog.csdn.net/Doris1104/article/details/50583393
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞