POJ 3984 迷宫问题

题目链接:POJ 3984 迷宫问题

题目大意:

题解:
典型的搜索走迷宫题,用pre来记录上个位置,递归输出路径。

#include <iostream>
using namespace std;

int mat[5][5];
int dis[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
struct node {
	int x, y, pre;
} que[50];
int head, tail;
bool visit[5][5];

void bfs() {
	que[0].x = 0, que[0].y = 0, que[0].pre = -1;
	tail++;
	visit[0][0] = true;
	while (head < tail) {
		for (int i = 0; i < 4; ++i) {
			int xi = que[head].x + dis[i][0];
			int yi = que[head].y + dis[i][1];
			if (xi < 0 || xi > 5 || yi < 0 || yi > 5 || mat[xi][yi] || visit[xi][yi]) {
				continue;
			}
			que[tail].x = xi;
			que[tail].y = yi;
			que[tail].pre = head;
			tail++;
			visit[xi][yi] = true;
			if (xi == 4 && yi == 4) {
				return;
			}
		}
		head++;
	}
}

void print(node now) {
	if (now.pre == -1)
		cout << "(" << now.x << ", " << now.y << ")" << endl;
	else {
		print(que[now.pre]);
		cout << "(" << now.x << ", " << now.y << ")" << endl;
	}
}

int main() {
	for (int i = 0; i < 5; ++i) {
		for (int j = 0; j < 5; ++j) {
			cin >> mat[i][j];
		}
	}
	bfs();
	print(que[tail - 1]);
	return 0;
}
posted @ 2020-10-05 17:49  ZZHHOOUU  阅读(418)  评论(1编辑  收藏  举报