poj3984 迷宫问题 bfs

链接:http://poj.org/problem?id=3984

迷宫问题

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 16884 Accepted: 10073

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,要求打印路径,其实用一个数组存就好

代码:

#define _CRT_SBCURE_MO_DEPRECATE
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>  
using namespace std;

const int MAXN = 100000 + 10;
int n, sx, sy, ex, ey;
int vis[305][305];
int dirt[8][2] = { { 1,0 },{ 0, 1 },{ -1,0 },{ 0, -1 } };
int x[10][10];//迷宫



struct node {
	int x;
	int y;
	int j;
	int step[105][3];
};

int judge(int x, int y) {
	if (x < 0 || x>5 || y < 0 || y>5) return 1;
	else return vis[x][y];
}
void bfs() {
	sx = 0; sy = 0;
	ex = 4; ey = 4;
	memset(vis, 0, sizeof(vis));
	queue<node>q;
	node a, b, next;
	a.x = sx;
	a.y = sy;
	a.j = 0;
	a.step[0][0] = a.x;
	a.step[0][1] = a.y;
	//cout << sx << sy;
	q.push(a);
	vis[sx][sy] = 1;
	while (!q.empty()) {
		b = q.front();
		q.pop();
		if (b.x == ex&&b.y == ey) {
			for (int k = 0; k < b.j; k++)
				cout << "(" << b.step[k][0] << ", " << b.step[k][1] << ")" << endl;
			cout << "(4, 4)" << endl;
		}
		for (int i = 0; i < 4; i++) {
			next = b;
			next.x = b.x + dirt[i][0];
			next.y = b.y + dirt[i][1];
			if (judge(next.x, next.y) == 1)continue;
			if (x[next.x][next.y] == 1)continue;//p判断不是墙
			(next.j)++;		
			next.step[next.j][0] = next.x;
			next.step[next.j][1] = next.y;
			q.push(next);
			vis[next.x][next.y] = 1;
		}
	}
		
}

int main()
{
	for (int i = 0; i<5; i++) {
		scanf("%d %d %d %d %d", &x[i][0], &x[i][1], &x[i][2], &x[i][3], &x[i][4]);
	}
	bfs();
	//system("pause");
	return 0;
}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/migu77777/article/details/52950145
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞